首页 > 其他分享 >.net6之微信支付宝支付

.net6之微信支付宝支付

时间:2025-01-21 13:32:52浏览次数:1  
标签:支付宝 公钥 wechatoptionsAccessor 微信 await 之微信 支付 var net6

概念

微信支付

1, 网页生成二维码,扫码付款
2, h5支付(非微信浏览器)
3, 微信浏览器支付
4, app支付
5, 面对面支付(扫用户生成二维码,扫码枪场景)

支付宝支付

1, 网页生成二维码,扫码付款
2, h5支付
3, app支付
4, 面对面支付(扫用户生成二维码,扫码枪场景)
依赖开源nuget包

注入使用

var builder = WebApplication.CreateBuilder(args);
// 添加Paylink依赖注入
builder.Services.AddAlipay();
builder.Services.AddWeChatPay();

builder.Services.Configure<AlipayOptions>(builder.Configuration.GetSection("Alipay"));
builder.Services.Configure<WeChatPayOptions>(builder.Configuration.GetSection("WeChatPay"));

参数参考

  // 支付宝
  // 更多配置,请查看AlipayOptions类
  "Alipay": {

    // 注意: 
    // 若涉及资金类支出接口(如转账、红包等)接入,必须使用“公钥证书”方式。不涉及到资金类接口,也可以使用“普通公钥”方式进行加签。
    // 本示例默认的加签方式为“公钥证书”方式,并调用 CertificateExecuteAsync 方法 执行API。
    // 若使用“普通公钥”方式,除了遵守下方注释的规则外,调用 CertificateExecuteAsync 也需改成 ExecuteAsync。
    // 支付宝后台密钥/证书官方配置教程:https://opendocs.alipay.com/open/291/105971
    // 密钥格式:请选择 PKCS1(非JAVA适用),切记 切记 切记

    // 应用Id
    // 为支付宝开放平台-APPID
    "AppId": "2021032966",

    // 支付宝公钥 RSA公钥
    // 为支付宝开放平台-支付宝公钥
    // “公钥证书”方式时,留空
    // “普通公钥”方式时,必填
    "AlipayPublicKey": "MIIBIjANBgkqhkiG9w0BAQEFACgKCAQEAgzDBCxe06JN4HYOGiAUMwPrI8PZR8aN7rj4XlJmjgpFNZkPHpoS2pjCSs1FQWDJATW+vSxeXINmLwbTwHuOuudF6RyQ/Wa7y2QrNjIhEzthaEFUw4ODzFVvk7iEEI1j8j2Xit3NNaXcwZps+YxQpYxb26c7VkU9b6Crk3ijt+IXTvUxWYenJece61ZzafK/BPsC/A8Mc6wWcn7c2DziuhPCkMp7wTrHk1OEQ9Fgif8a3RQN0Ea9WRDc0kThO/nK6cJY8YeuyVaWQZ5fWgOzFg2Odr85FzAs3fq37G3gF1D23jmX6rucijdMby8iZp/A8loenbLJXVMd7XpdmNt/odwIDAQAB",

    // 应用私钥 RSA私钥
    // 为“支付宝开放平台开发助手”所生成的应用私钥
    "AppPrivateKey": "MIIEpQIBAAKCAQEAqBD529HPc5Ps3nBY+BrCErh3oEMx0ZeAGwsbaQ/tsMxu9Qc9O+gkm9rOMab9ydfORu9FwU98+2Tj/1govn0qcZuU63O3mleHfeu0eM+JIT2suZ9PZ3+4ILgeW7W0aQz2iaSgdDBJ95OAVxyTzPC2O1zzFLI+jvcrGs/pN+g6fvuhTe3MXhJAW7ZkjUJfHvNBvay2IM7sTuXoXL05RsIMVxuD0A/utxszeMQ//HcAho17tQdyV166Ach+1dxPDddvilX8c/mDYnFFolIHcV2conTCYwdroKqCnU0/1Tf85XZNEb87LGWUc4UyjdTW89M0VBquO6rvmjyLEkvbTOA40wIDAQABAoIBAQCCSMaodTkQK7gPp6AQlQ2lXYK+pdhU1dDlJfMVutdTmubY48fATPE0MKZvLzjF45lwu8OjW29Top5sL3dGU9k3QJhs/cNyzi+mmbXJgXiYYCspqinv3b5q/s/p4C3+Nr8Ty87psmSodHWQTlGijQpW1HjZ7wVZ9dfj0WWaJhQd7PA1zZfLpoXO0KLCZjP6NZdz+MRgw9AoGAMWy07iKO6MNESB6u14khDrsSpUhYK5FGO9/jH4zj9IQOttkjrri4HFkS3L/+2WbUq2dVsQzf+KBqDelVD6pkFCjcGyQ7TE40+z1WWL2vv8PbT7ol+ZxyQwgx8INl+GqH3BL+ca3Al8SVk6GxIjOtMsflpWz97526u3Ge33LmF50CgYEAqAtHv5pCrSG79zqptamFmpr3hhANwAQTvNtrcL3BJxwvUO0GDgq54GfKs9Wj7YcErLZ6KiTy8GgY/Domj40wsGBhYew6ASyA/VpUg9Vosa3ZpluNIlj4K49bDX3BeA43+OKFrke8FEGNLfDnnWW/wLR0mAooALeDgNT89NTPhRECgYEA48gTUF4rd1Qw6d3CQp8eKWPxB7tlQoFJR6Z1bbeFuqxD+8eTL+tSVLTzyx6eNEAIDhRtGpY17WNbxgKvDDJITef0Q1zJ3+801HQrM4qCh0ov9/Z9gWvk0MB2UZxFGiIuPa5SGogiWufXJG5lWIFG/rGvVYZoQ9pZ5OK8PCNdjWY=",

    // 服务网关地址
    // 默认为正式环境地址
    "ServerUrl": "https://openapi.alipay.com/gateway.do",

    // 签名类型
    // 支持:RSA2(SHA256WithRSA)、RSA1(SHA1WithRSA)
    // 默认为RSA2
    "SignType": "RSA2",

    // 应用公钥证书
    // 可为证书文件路径 / 证书文件的base64字符串
    // “公钥证书”方式时,必填
    // “普通公钥”方式时,留空
    "AppPublicCert": "",

    // 支付宝公钥证书
    // 可为证书文件路径 / 证书文件的base64字符串
    // “公钥证书”方式时,必填
    // “普通公钥”方式时,留空
    "AlipayPublicCert": "",

    // 支付宝根证书
    // 可为证书文件路径 / 证书文件的base64字符串
    // “公钥证书”方式时,必填
    // “普通公钥”方式时,留空
    "AlipayRootCert": ""
  }

  // 微信支付
  // 更多配置,请查看WeChatPayOptions类
  "WeChatPay": {
   
    // 如:微信公众平台AppId、微信开放平台AppId、微信小程序AppId、企业微信CorpId等
    "AppId": "wx0a86fcdcb007",
    //公众号的appsecret 原定义企业微信的AppSecret这里临时使用
    "AppSecret": "1a7fce61ab27438cd11d7c3e",


    // 商户号
    // 为微信支付商户平台的商户号
    "MchId": "16583823",

    // 商户API密钥
    // 为微信支付商户平台的API密钥,请注意不是APIv3密钥
    "APIKey": "12345efghjjjjkkkkeeqqEGf",

    //"APIKey": "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDBea4p8oagWR02P9IvHZZjPmU+xb+Kbowl3Gr+OtyZPlgVHfmXdlWTJut/X3ffCvQ5jv0qM4MRbiCd1QgOlenaT6SRqoLHITaj+CFnPcRUyAOvZzgL/woffw5ZA7SPmeqPDjsQiGVig0iyT1IQFYMXQidJyxawcxvrzFQ+nV8OLKtFZUpEycyDjrkEFkS0pgvGho5w20+2DK27PiL7VCghE21i2irz19XeiyTnSGC9TijXfiSBad+N+m5VQwlxjAgQN7HrnlVYln6IRQa7e/a/KcQuE5KTNIRSNIyg1O/l059dIxPFJRmj2GuPkCyBhu8NX/IHsw05mwoYceBtcOIf9L6ESTEf+28CkgN4jv1gGmLb9I/wfQKBgQDjk6iS4YpK5nGfaUTEYIWu7iTquDn7YnFPrj1LQVEpaYyGy34Bee2CcZnzq6nkrkADWEffcS3EmizzRpSQ0AlOu4yM7Z562p01thWAjb1vL66+mBoEwCFXDWB5fYCqRGYJYEhlxFiolYMSIGnJugOufz2q2qkQbUYC2eaM2xy39wKBgQDZo7DlBXLks8W6nbhOlz0IBp6dAWT6CJ0MBDJNEXob73A8+u+95G1/YJ0gECULf86fgIfn9eYffv0h2OJPYZnoONtQHcjaZWcWLFD+eH6AaEuCXMI4JqfDoPShQSmBqJ0CAyEGQ8X1+EBRcfXsVT3DItyuHtzbCdaiQ6PBOsaguwKBgDLR54QdX4+IVHk/vb6Iu3Gr9ox/5VrQyfL8Ou3SQTiZPGthh9r2imZlzfZPMFpD20Gj9jDcilbsAvu0mDqaammtkh5qdciDhzXWWojhnhr1L/WZ672B1jAlaZTXxOLA8XRIjwJCzXWgJavnlxgYNPhDq9a6i6SCcm7yj/yGdaxTAoGAfv49/RT12q9vhBn97pXfPeym5tRmeGNISDe2pjO5fc10P5DpDXPZ1MaqSIhDJXeZOIcGRnq8oco2qGZmf41jAhcTGaeXiKA8y7pmNGZY4lJ5JQM9LQiZQdSMif982bRqkT8EKSSowYLu/NczeYivtkqEXHGTy5ftDtfLGLhUKHsCgYAiNJa4R3J5mao8Yyu41Aw0y82LTqOu1zJHJhcqj1eBodJBA5DB2w/k5sYXTCPzHfVvogjZoD2tbgLEnAfTbV0vFeUNOP3QFfxhmolCGwAaqcHyO9DMeYY8sLMfwIRyXwyrqpCiz/cmvq92poyMScSMPeJlV/83QXfh+y0HG0bIxg==",

    // 商户APIv3密钥
    // 为微信支付商户平台的APIv3密钥,请注意不是API密钥,v3接口必填
    "APIv3Key": "12345bcdefghjjjjkkkkeeqqEuh",

    // 商户API证书
    // 使用V2退款、付款等接口时必填
    // 使用V3接口时必填
    // 可为证书文件路径 / 证书文件的base64字符串
    "Certificate": "MIIEITCCAwmgAwIBAgIUIV5gD58qbZtCIfoV/GGzsxdWJ3EwDQYJKoZIhvcNAQELBQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsTFFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuzkWcLzmqFAW179HSkbO5MIqoArx5nC0DOhA86xS6zWEi89UZ3vrQDVsMjd4Gsyv2Ph/DFLYjCjns1WIGcskvniD8xhe0qWXqSIUCkOrP7vRYc3mZKJbanJ2hJNlOdQOUkQIDAQABo4G5MIG2MAkGA1UdEwQCMAAwCwYDVR0PBAQDAgP4MIGbBgNVHR8EgZMwgZAwgY2ggYqggYeGgYRodHRwOi8vZXZjYS5pdHJ1cy5jb20uY24vcHVibGljL2l0cnVzY3JsP0NBPTFCRDQyMjBFNTBEQkMwNEIwNkFEMzk3NTQ5ODQ2QzAxQzNFOEVCRDImc2c9SEFDQzQ3MUI2NTQyMkUxMkIyN0E5RDMzQTg3QUQxQ0RGNTkyNkUxNDAzNzEwDQYJKoZIhvcNAQELBQADggEBAGsppQd4wiLABM+lxrIR+OaQv1lkiSU4NFnhJWYaYFpE1Eq1/KS3+hqKRChKQOBreqgztShYw8XpEpa4AV2E+2rUbKwFnRxkAvRoHoS0lhnrgDmZvnnj/YKe9dc1XJaWywLjXDhdyTNCqAP0kxybBX8MCDExawspdKjw0vyC5GTxV4Vp+92htxhsVjDb3/2l2bkcYNtZ0ysEFBft4EVo8FTzsbQOP4D+4ZvCDfM4UiT/V/9eEsp/YF8bcs0TOlMwSdzU0rXl7XiUh3JPENewWh0TS3mMVRUoQ4av3rPMFV0HHz2q5fWZR7oMBAzspI+GtUValuAan7G22Hu1L3u/5rU=",

    // 商户API私钥
    // 当配置了P12格式证书时,已包含私钥,不必再单独配置API私钥。
    // PEM格式证书,需要单独配置。
    "APIPrivateKey": "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC2LR4f/E87IsEbMeCBIwPYV8KUOrSo1qr2UyQEwjOsxgt2yQdIP5Zex3XLeMUGcLQmQPHrNeAhyTFYPmcFWMJZ6fXwGjycT7N0quSGfTJaaTZrei1B/6xSbA59eCpkN9gy5tAgHO1CKvSU/eqmab4aHWzZykF519buR4Lr7je04ZbSWyfu2Fje05YXGrPjtKPhpBw+hzZUZqPyGH/X73LORZwvOaoUBbXv0dKRs7kwiqgCvHmcLQM6EDzrFLrNYSLz1Rne+tANWwyN3gazK/Y+H8MUtiMKOezVYgZyySEmM4t8WfjuZCgCTJQAGr68kWcwkgoM40SLeVXk4VlWRlRUS5I1Fg9s4ycfO7YB5iOcjdWhDBipEGAnX3GSmGWDhD0hRBpb0CgYEAyOKgNUTfrQMUgJgy7BYFD3uE6mLIn1AkEs96pymjvjXICFx2fkjDcEfzwTTfBFfyKIgerDr1kbBxBXVBkMwzTrnNx0pvIGACe2UNgeEEI7aaf2RQ7K181D9Yvt0/HZd4PcJ3bb87HOXJcDCLK+DntbFoYzWhX6XyM3ayDQcqhWUCgYEAow51QyvkCKwTw09gJuFTD3v1lGFskLt9Qp3pdwxMbvKAd9lVGyFFYE0LKfZrYrrhSsup7UqS3rbRxDZoSbrF3IohPvuXVhtWct7jo5xPjGIIGuLGSFwzkJ/Y+RPRrNqlbfNZPuvfOR1eBBPuVCncpcRCIkxUZxnhP+kUyWJs0UkCgYBL0wbHtIx9AHmfpFMsO4+DbYsY8Vpqj9Rd6USRji0JIcG0Ljpnpk1mtzHxjmRTfmKgG+j/920zpZazibPK1NjU8VsTyyuw26x0KQt1J5rpZAZi6VmGTGGet55mxJoLMF4paZqsqQ7F9JIZL6mIUWcEdMdDEz4rHTcTZ80DD95j5QKBgQCyK74ZHk3jwTAty5/u7fbU1f21+8phqPElfyn/O7FkjcoHP+Bzo5dHjXwU/I/bfNvQ9y8Uan8scHDmXW/RXKC/dbgRRc5VKux0J55PHHkfy0NOxGPBIu3oua6JI7r+OnhngM4QJ6yRNXU/XdIiDkg5oviZ8lNpd8nf1Mi03s1Dbg==",


    // RSA公钥
    // 目前仅调用"企业付款到银行卡API [V2]"时使用,执行本示例中的"获取RSA加密公钥API [V2]"即可获取。
    "RsaPublicKey": ""

  },

微信支付


//前端判断环境 h5还是app 微信是否是微信浏览器,
	/* #ifdef H5 */
					if (typeof WeixinJSBridge === 'undefined') {
						_this.orderWechatH5PagePay(_this.goodsId);
					} else {
						await _this.queryOpenId(_this.goodsId);
					}
					/*#endif*/
是否是app
/*#ifdef APP-PLUS*/
	/*#endif*/

//后端实现
        private readonly ApiRequestUrl _apiRequestUr1;
        private readonly IAlipayClient _aliclient;
        private readonly IWeChatPayClient _wechatclient;
        private readonly IOptions<AlipayOptions> _alioptionsAccessor;
        private readonly IOptions<WeChatPayOptions> _wechatoptionsAccessor;
        private readonly ReturnInfo _returnInfo;
        private readonly IOrderService _orderService;
      public PayService(IServiceProvider serviceProvider, 
            IAlipayClient client,
              IWeChatPayClient wechatclient,
            IOrderService orderService,
        IOptions<AlipayOptions> optionsAccessor,
        IOptions<WeChatPayOptions> wechatoptionsAccessor,
             IOptions<ReturnInfo> returnInfo,
             ApiRequestUrl apiRequestUr1
        ) : base(serviceProvider)
        {
           
            _aliclient = client;
            _wechatclient = wechatclient;
            _alioptionsAccessor = optionsAccessor;
            _returnInfo=returnInfo.Value;
            _wechatoptionsAccessor = wechatoptionsAccessor;
            _orderService = orderService;
            _apiRequestUr1= apiRequestUr1;
        }


  /// <summary>
        /// PC网站微信根据订单支付(返回二维码)
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>

        public async Task<string> WechatPagePay(string orderId)
        {
            //获取订单信息
            var order = await _dbContext.Queryable<Order>().Where(x => x.Id == orderId).FirstAsync();
            //判断当前商品是否已经被购买
            var request = new WeChatPayUnifiedOrderRequest
            {
                Body = "商品编号" + order.UniqueNo,
                OutTradeNo = order.OrderNo,
                TotalFee = (int)(order.OrderAmount * 100),
                SpBillCreateIp = "127.0.0.1",
                NotifyUrl = _returnInfo.WechatNoticeUrl,
                TradeType = "NATIVE",
            };

            var response = await _wechatclient.ExecuteAsync(request, _wechatoptionsAccessor.Value);
            return response.CodeUrl;
        }
    //后端实现 使用V3版本
    /// <summary>
        /// 微信 H5支付 (充值,非微信浏览器)
        /// </summary>
        /// <param name="viewModel"></param>

        public async Task<WeChatPayUnifiedOrderResponse> WechatH5PagePayRecharge(string recordId)
        {
            //获取充值记录
            var record = await _dbContext.Queryable<Rechargerecord>().Where(x => x.Id == recordId).FirstAsync();
            if (record == null) return null;
            
            var request = new WeChatPayUnifiedOrderRequest
            {
                Body = "商品编号" + record.Id,
                OutTradeNo = record.Number,
                TotalFee = (int)(record.Money * 100),
                SpBillCreateIp = HttpContext.Connection.RemoteIpAddress.ToString(),
                NotifyUrl = _returnInfo.WechatNoticeUrl,
                TradeType = "MWEB",
            };

            WeChatPayUnifiedOrderResponse response = await _wechatclient.ExecuteAsync(request, _wechatoptionsAccessor.Value);
            return response;
        }

前端使用

	//微信支付 非微信浏览器
			async orderWechatH5PagePay(goodsId) {
				const res = await this.$api.orders.WechatH5PagePayRechargepay(goodsId);
				if (res.code == 200) {
					document.location.href = res.content.mwebUrl +
						`&redirect_url=${this.urlencode('https://tt1236.com/#/pages/my/index')}`;
				}
			},


  //微信浏览器支付
//后端实现 使用V3版本
     /// <summary>
        /// 微信公众号支付-JSAPI下单(h5充值)
        /// </summary>
        /// <param name="viewModel"></param>
        public async Task<object> PubPayRecordAsync(PubPayRecordRequest pubPayRecordRequest)
        {
     
            //获取充值记录信息
            var order = await _dbContext.Queryable<Rechargerecord>().Where(x => x.Id == pubPayRecordRequest.RecordId).FirstAsync();
            if (order == null) return null;

            //获取OpenId
            var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + _wechatoptionsAccessor.Value.AppId + "&secret=" + _wechatoptionsAccessor.Value.AppSecret + "&code=" + pubPayRecordRequest.Code + "&grant_type=authorization_code";
            var weChat = HttpHelp.HttpWebRequest<object>(url, "", Encoding.UTF8, HttpHelp.Method.GET);

            var topkenResponse = JsonConvert.DeserializeObject<WechatTokenResponse>(weChat.ToString());
            if (topkenResponse == null || string.IsNullOrEmpty(topkenResponse.openid)) return null;
            // return response;
            var model = new WeChatPayTransactionsJsApiBodyModel
            {
                AppId = _wechatoptionsAccessor.Value.AppId,
                MchId = _wechatoptionsAccessor.Value.MchId,
                Amount = new Essensoft.Paylink.WeChatPay.V3.Domain.Amount { Total = (int)(order.Money * 100), Currency = "CNY" },
                Description = "充值编号" + order.Number,
                NotifyUrl = _returnInfo.WechatNoticeUrl,
                OutTradeNo = order.Number,
                Payer = new PayerInfo { OpenId = topkenResponse.openid }
            };

            var request = new WeChatPayTransactionsJsApiRequest();
            request.SetBodyModel(model);

            var response = await _wechatclient.ExecuteAsync(request, _wechatoptionsAccessor.Value);
              if (!response.IsError)
            {
                var req = new Essensoft.Paylink.WeChatPay.V3.Request.WeChatPayJsApiSdkRequest
                {
                    Package = "prepay_id=" + response.PrepayId
                };
              
                var parameter = await _wechatclient.ExecuteAsync(req, _wechatoptionsAccessor.Value);
               // return parameter.MapTo<WechatRtnResponse>();
                 return parameter;
            }
            return null;

        }

//前端实现

//获取当前用户openid 微信浏览器
			async queryOpenId(goodsId) {
				var redirectUri = 'http://tt3246.com/#/pages/my/yajinchongzhi/index?id=' + goodsId +
					"&goodsId=2&name=555";

				var url =
					'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx82a92ca40d09407d&redirect_uri=' +
					encodeURIComponent(redirectUri) +
					'&response_type=code&scope=snsapi_base#wechat_redirect';

				document.location.href = url
			},


// 页面加载时存在code 表示当前页面为微信浏览器支付回调页面

var code = this.getUrlValue('code');
			if (code) {
				this.recordId = option.id;
				//唤起微信浏览器支付
				await this.wechatpayv3PubPay({
					"recordId": option.id,
					"code": code
				});
			}

	async wechatpayv3PubPay(data) {
				const res = await this.$api.orders.PubPayRecordpay(data);
				if (res.code == 200 && res.content != null) {
					await this.onBridgeReady(res.content);
				} else {
					if (res.content == null) {} else {
						// uni.showToast({
						// 	title: '请重新支付',
						// 	icon: 'none'
						// })
					}
				}
			},
	onBridgeReady(data) {
				//获取后端参数
				var _this = this;
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": data.appId, //公众号名称,由商户传入     
						"timeStamp": data.timeStamp, //时间戳,自1970年以来的秒数     
						"nonceStr": data.nonceStr, //随机串     
						"package": data.package,
						"signType": data.signType, //微信签名方式:
						"paySign": data.paySign //微信签名 
					},
					function(res) {
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							uni.showLoading({
								title: '支付验证中...',
								mask: true,
							});

							_this.IsPay();
							// 使用以上方式判断前端返回,微信团队郑重提示:
							//res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
						} else if (response.err_msg == "get_brand_wcpay_request:cancel") {
							// 支付失败的处理逻辑 
							uni.showToast({
								title: '取消支付',
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							})


						}
					}
				);

			},


//后端实现v3版本 app支付

       /// <summary>
        /// 微信app支付
        /// </summary>
        /// <param name="viewModel"></param>
        public async Task<object> AppPayRecordAsync(string recordId)
        {

            //获取充值记录信息
            var record = await _dbContext.Queryable<Rechargerecord>().Where(x => x.Id == recordId).FirstAsync();
            if (record == null) return null;        
            var model = new WeChatPayTransactionsAppBodyModel
            {
                AppId = _wechatoptionsAccessor.Value.AppId,
                MchId = _wechatoptionsAccessor.Value.MchId,
                Amount = new Essensoft.Paylink.WeChatPay.V3.Domain.Amount { Total = (int)(record.Money * 100), Currency = "CNY" },
                Description = "充值编号" + record.Number,
                NotifyUrl = _returnInfo.WechatNoticeUrl,
                OutTradeNo = record.Number
            };
            var request = new WeChatPayTransactionsAppRequest();
            request.SetBodyModel(model);

            var response = await _wechatclient.ExecuteAsync(request, _wechatoptionsAccessor.Value);

            if (!response.IsError)
            {
                var req = new Essensoft.Paylink.WeChatPay.V3.Request.WeChatPayAppSdkRequest
                {
                    PrepayId = response.PrepayId
                };

                var parameter = await _wechatclient.ExecuteAsync(req, _wechatoptionsAccessor.Value);
                return JsonConvert.SerializeObject(parameter);
            }
            return null;
        }


// 前端实现app支付

	/*#ifdef APP-PLUS*/
					
					var wechatapprtn = await this.$api.orders.AppPayRecordWECAHTORDER_URL(_this.goodsId);
					wechatapprtn.content = JSON.parse(wechatapprtn.content);
					var orderInfo = {
						"appid": wechatapprtn.content.appid, // 微信开放平台 - 应用 - AppId,注意和微信小程序、公众号 AppId 可能不一致
						"noncestr": wechatapprtn.content.noncestr, // 随机字符串
						"package": wechatapprtn.content.package, // "Sign=WXPay", // 固定值
						"partnerid": wechatapprtn.content.partnerid, // "148*****52", // 微信支付商户号
						"prepayid": wechatapprtn.content.prepayid, // "wx202254********************fbe90000", // 统一下单订单号 
						"timestamp": wechatapprtn.content.timestamp, // 1597935292, // 时间戳(单位:秒)
						"sign": wechatapprtn.content
							.sign  // 签名,这里用的 MD5/RSA 签名
					};
					console.log(orderInfo)
					if (wechatapprtn.code == 200 && wechatapprtn.content != null) {
						uni.requestPayment({
							"provider": 'wxpay',
							"orderInfo": orderInfo,
							success: function(res) {
								uni.showToast({
									title: "付款成功,即将跳转...",
									icon: 'none',
									duration: 1000
								});
								//等待两秒后跳转到
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/my/index'
									});
					
								}, 1000)
					
							},
							fail: function(err) {
								
								console.log('fail:' + JSON.stringify(err));
							}
						});
					}
					/*#endif*/

			
       

支付宝支付


//前端判断环境 h5还是app 
	/* #ifdef H5 */
					if (typeof WeixinJSBridge === 'undefined') {
						_this.orderWechatH5PagePay(_this.goodsId);
					} else {
						await _this.queryOpenId(_this.goodsId);
					}
					/*#endif*/
是否是app
/*#ifdef APP-PLUS*/
	/*#endif*/

//后端实现
        private readonly ApiRequestUrl _apiRequestUr1;
        private readonly IAlipayClient _aliclient;
        private readonly IWeChatPayClient _wechatclient;
        private readonly IOptions<AlipayOptions> _alioptionsAccessor;
        private readonly IOptions<WeChatPayOptions> _wechatoptionsAccessor;
        private readonly ReturnInfo _returnInfo;
        private readonly IOrderService _orderService;
      public PayService(IServiceProvider serviceProvider, 
            IAlipayClient client,
              IWeChatPayClient wechatclient,
            IOrderService orderService,
        IOptions<AlipayOptions> optionsAccessor,
        IOptions<WeChatPayOptions> wechatoptionsAccessor,
             IOptions<ReturnInfo> returnInfo,
             ApiRequestUrl apiRequestUr1
        ) : base(serviceProvider)
        {
           
            _aliclient = client;
            _wechatclient = wechatclient;
            _alioptionsAccessor = optionsAccessor;
            _returnInfo=returnInfo.Value;
            _wechatoptionsAccessor = wechatoptionsAccessor;
            _orderService = orderService;
            _apiRequestUr1= apiRequestUr1;
        }


//后端实现
 /// <summary>
        /// 充值支付宝手机h5支付
        /// </summary>
        public async Task<string> AliWapPayRecharge(string id)
        {
            //获取充值信息
            var rechargerecord = await _dbContext.Queryable<Rechargerecord>().Where(x => x.Id == id).FirstAsync();
           
            if(rechargerecord != null)
            {

                var model = new AlipayTradeWapPayModel
                {
                    Body = "充值编号" + rechargerecord.Number,
                    Subject = rechargerecord.Number,
                    TotalAmount = rechargerecord.Money.ToString(),
                    OutTradeNo = rechargerecord.Number,
                    ProductCode = "QUICK_WAP_WAY"
                };
                var req = new AlipayTradeWapPayRequest();
                req.SetBizModel(model);
                req.SetNotifyUrl(_returnInfo.AliNoticeUrl);
                req.SetReturnUrl(_returnInfo.AliReturnUrl);
                var response = await _aliclient.PageExecuteAsync(req, _alioptionsAccessor.Value);
               
                return response.Body;

            }
            return null;
          
        }


        /// <summary>
        /// APP支付宝支付
        /// </summary>
        public async Task<string> AppAliPayRechargeAsync(string id)
        { 
            //获取充值信息
            var rechargerecord = await _dbContext.Queryable<Rechargerecord>().Where(x => x.Id == id).FirstAsync();
            if (rechargerecord == null) return null;
            var model = new AlipayTradeAppPayModel
            {
                OutTradeNo = rechargerecord.Number,
                Subject = "代练" + rechargerecord.Number,
                ProductCode = id,
                TotalAmount = rechargerecord.Money.ToString(),
                Body = "充值编号" + id
            };
            var req = new AlipayTradeAppPayRequest();
            req.SetBizModel(model);
            req.SetNotifyUrl(_returnInfo.AliNoticeUrl);

            var response = await _aliclient.SdkExecuteAsync(req, _alioptionsAccessor.Value);
            // 将response.Body给 ios、android端,由其去完成调起支付宝APP。
            // 客户端 Android 集成流程: https://opendocs.alipay.com/open/204/105296/
            // 客户端 iOS 集成流程: https://opendocs.alipay.com/open/204/105295/
            return response.Body;
         
        }

//前端实现
   	if (_this.payType == 'isZfb') {
				
					/* #ifdef H5 */
					_this.AliWapPayRechargepay(_this.goodsId);
					/*#endif*/

					/*#ifdef APP-PLUS*/
					///获取app支付参数
					var aliapprtn=await this.$api.products.AppAliPayRechargeORDER_URL(_this.goodsId);
					if(aliapprtn.code==200){
						uni.requestPayment({
						    provider: 'alipay',
						    orderInfo: aliapprtn.content, //微信、支付宝订单数据 【注意微信的订单信息,键值应该全部是小写,不能采用驼峰命名】
						    success: function (res) {
							   uni.showToast({
							   	title: "付款成功,即将跳转...",
							   	icon: 'none',
							   	duration: 1000
							   });
							   //等待两秒后跳转到
							   setTimeout(() => {
							   	uni.navigateTo({
							   		url: '/pages/my/index'
							   	});
							   
							   }, 1000)
							   
						    },
						    fail: function (err) {
						        console.log('fail:' + JSON.stringify(err));
						    }
						});
					}
				

					/*#endif*/

				} 

	async AliWapPayRechargepay(id) {
				const res = await this.$api.orders.AliWapPayRechargepay(id);
				if (res.code == 200) {
					//将接口返回的Form表单显示到页面
					// let form='后端返回的支付宝表单数据'
					const div = document.createElement('formdiv');
					div.innerHTML = res.content;;
					document.body.appendChild(div);
					document.forms[0].submit();
					div.remove();
				}
			},

标签:支付宝,公钥,wechatoptionsAccessor,微信,await,之微信,支付,var,net6
From: https://www.cnblogs.com/inclme/p/18683132

相关文章

  • 20250116 支付宝出现重大事故 有感
    事故20250116下午支付宝直接冲上微博热搜榜首,原因是在2025年01月16日14:40-14:45期间出现大量支付显示“政府补贴”减免字样。最开始我是在小红书上看到的相关内容,只是看到这个图片,心想这肯定是小红书暗广,撇了一眼就划过了。当“支付宝出现重大BUG”出现在微博头条时,才确信此事......
  • 支付宝P0事故,订单减免20%
    大家好,我是小悟。2025年1月16日下午,支付宝发生了一件引人瞩目的事件。在14:40-14:45短短五分钟内,众多用户发现使用支付宝进行个人转账、信用卡还款、缴费、购票等各类操作时,订单被提示享受“政府补贴”,直接减免20%。从影响范围来看,这一事件的影响十分广泛。它涉及支付宝多......
  • 从支付宝P0事故处理方案,合理推测损失金额
    支付宝昨天(2024-01-16)的无差别"送钱"的事儿,大家都知道了吧。具体的,就是在昨天14:40~14:45期间,所有支付宝的支付订单都被减免了20%,减免原因在界面上显示为"政府补贴"。这里指的订单,是指所有通过支付宝产生的交易,包括「购物、信用卡、生活缴费、个人转账」等等,而且和此前(消......
  • 错失一个亿,支付宝 P0级事故,整整5分钟......网友戏称:错过的羊毛犹如砒霜
    今日份碎碎念:就在昨日下午,支付宝突然出现了一起“重大意外事件”,不晓得大家有没有在网络上刷到相关消息?简单来讲,在昨天下午14:40至14:45这短短5分钟的时段里,当用户在进行转账、购物、购票、还款等各类操作时,在订单支付页面均出现了“政府补贴”的提示,且显示减免优惠......
  • 支付宝分分动物运动会,支付宝三分动物运动会,分分动物运动会,三分动物运动会的游戏详细介
    支付宝动物运动会是支付宝应用内一项趣味性的活动,它允许用户通过参与虚拟的动物比赛来获取一些奖励或者积分。这类活动本质上是一种营销手段,旨在增加用户与支付宝平台的互动,提升用户粘性和活跃度。由于活动是在支付宝这一正规、受监管的金融服务平台内进行,因此其背后有严格的运......
  • uniapp精仿支付宝UI界面,首页/理财/消息/生活/口碑/我的,还有模拟支付宝扫码支付/收付款
    uniapp精仿支付宝UI界面,首页/理财/消息/生活/口碑/我的,还有模拟支付宝扫码支付/收付款等功能,界面漂亮颜值高,视频商城小工具等,蚂蚁森林种树养鸡农场偷菜样样齐用于视频,商城,直播,聊天等sumer-alipay介绍uniapp精仿支付宝UI界面,首页/理财/消息/生活/口碑/我的,还有模拟支付宝......
  • 支付宝动物运动会,动物运动会,运动会,动物运动会官方网站结果 ...
    探索欢乐无限的支付宝动物运动会,尽在zfbgame.com!亲爱的用户们,想象一下,在这个特别的线上竞技场里,不同的小动物们带着他们的速度与激情,进行一场激动人心的比赛!欢迎访问我们的网站zfbgame.com,加入支付宝动物运动会的盛大赛事,开启一段欢乐的冒险之旅!在这里,你将见证六位活泼可爱......
  • 支付宝动物运动会官方API接口,动物运动会官方API接口,动物运动会比赛结果API,运动会API,支
    2025年最热、最火爆的游戏——支付宝动物运动会,正在如火如荼地进行!超强的三方监管机制让得这场赛事达到了公平、公正、公开,三方监管平台分别是:支付宝官方APP、游戏官网 www.zfbgame.com 以及淘宝APP共同携手,确保每一位参与者的权益!支付宝动物运动会是支付宝应用内一项趣味性......
  • .net6之阿里云OSS
    概念集成阿里云OSS文件存储服务引用阿里云包封装AliyunSmsClient(二次封装阿里云短信基类)publicclassAliyunOssClient{privatereadonlyAliyunOssOptions_options;privatereadonlyOssClient_client;publicAliyunOssClient(IOpt......
  • uniapp精仿支付宝UI界面,首页/理财/消息/生活/口碑/我的,还有模拟支付宝扫码支付/收付款
    uniapp精仿支付宝UI界面,首页/理财/消息/生活/口碑/我的,还有模拟支付宝扫码支付/收付款等功能,界面漂亮颜值高,视频商城小工具等,蚂蚁森林种树养鸡农场偷菜样样齐用于视频,商城,直播,聊天等sumer-alipay介绍uniapp精仿支付宝UI界面,首页/理财/消息/生活/口碑/我的,还有模拟支付宝......