首页 > 编程语言 >支付宝小程序支付及支付后异步通知 C# NeCore3.1

支付宝小程序支付及支付后异步通知 C# NeCore3.1

时间:2024-11-28 17:55:38浏览次数:5  
标签:string get C# id 支付 using model NeCore3.1 public

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

1、支付异步通知

using AliyunHelper.AliPayHelper;
using Aop.Api.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SugarDbContext;
using swapCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace swapAlipay.Controllers
{
    /// <summary>
    /// https://github.com/alipay/alipay-easysdk/tree/master/csharp
    /// https://www.cnblogs.com/carlpeng/p/13468878.html
    /// </summary>
    [AllowAnonymous]
    public class ReviceController : BaseController
    {
        private readonly ILogger<ReviceController> logger;

        public ReviceController(ILogger<ReviceController> logger)
        {
            this.logger = logger;
        }

        /// <summary>
        /// Alipay回调通知
        /// 
        /// {"app_id":"","auth_app_id":"","body":"租赁","buyer_logon_id":"1***@qq.com","buyer_open_id":"","buyer_pay_amount":"0.01","charset":"UTF-8","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","gmt_create":"2024-11-28 14:51:11","gmt_payment":"2024-11-28 14:51:19","invoice_amount":"0.01","merchant_app_id":"2021004195648040","notify_id":"2024112801222145120091841466598371","notify_time":"2024-11-28 14:51:20","notify_type":"trade_status_sync","out_trade_no":"","point_amount":"0.00","receipt_amount":"0.01","seller_email":"chenwolong2022@163.com","seller_id":"2088260077052221","sign":"","sign_type":"RSA2","subject":"租赁","total_amount":"0.01","trade_no":"","trade_status":"TRADE_SUCCESS","version":"1.0"} 
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("AliPayNotify")]
        public ActionResult AliPayNotify()
        {
            logger.LogError("AliPayNotify---支付宝回调---开始");
           
            string result = "success";
            SortedDictionary<string, string> sarray = new SortedDictionary<string, string>();
            var keys = Request.Form.Keys;

            if (keys != null)
            {
                foreach (string key in keys)
                {
                    sarray.Add(key, Request.Form[key]);
                }
            }
          
            logger.LogError(JsonConvert.SerializeObject(sarray));
            if (sarray.Count > 0)
            {
                string app_id = Request.Form["app_id"];
                var alipayConst = AlipayConst.GetAliPayConst(app_id);
                //alipayPublicKey 支付宝公钥  Charset:UTF-8  SignType:RSA2
                var safe = AlipaySignature.RSACheckV1(sarray, alipayConst.alipayPublicKey, alipayConst.Charset, alipayConst.SignType, false);

                if (safe) //验签成功 && 关键业务参数校验成功
                {
                    string out_trade_no = Request.Form["out_trade_no"];   //获取ali传过来的参数的值
                    string trade_no = Request.Form["trade_no"];
                    string trade_status = Request.Form["trade_status"];
                    string total_amount = Request.Form["total_amount"];
                    string buyer_id = Request.Form["buyer_id"];
                    string buyer_logon_id = Request.Form["buyer_logon_id"];

                    if (trade_status != "TRADE_SUCCESS")
                    {
                        result = "fail";
                    }
                    else
                    {
                        //具体业务
                    }
                }
                else//验证失败
                {
                    result = "fail";
                }
            }
           
            return Content(result);
        }
         

    }

    
}
View Code

2、支付代码

using System;
using System.Collections.Generic;
using Aop.Api;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Domain;
using Aop.Api.Util;
using AliyunHelper.AliPayHelper.AlipayModels;

namespace AliyunHelper.AliPayHelper
{


    public class AlipayTradeHelper
    {
        public static AlipayTradeCreateResponse CreateAliOrder(AlipayTradeDto data)
        {
            var parm = AlipayConst.GetAliPayConst(data.AppId);
            // 初始化SDK
            IAopClient alipayClient = new DefaultAopClient(GetAlipayConfig(parm));
            // 构造请求参数以调用接口
            AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
            AlipayTradeCreateModel model = new AlipayTradeCreateModel();
            request.SetNotifyUrl(parm.NotifyUrl);
            // 设置商户订单号
            model.OutTradeNo = "Ali" + DateTime.Now.ToString("yyyyMMddHHmmssfff");

            // 设置产品码
            model.ProductCode = "JSAPI_PAY";

            // 设置小程序支付中
            model.OpAppId = data.AppId;

            // 设置订单总金额
            model.TotalAmount = data.TotalAmount;


            // 设置可打折金额
            model.DiscountableAmount = data.DiscountAmount;

            // 设置订单标题
            model.Subject = "租赁";

            // 设置订单附加信息
            model.Body = "租赁";

            // uid参数未来计划废弃,存量商户可继续使用,新商户请使用openid。请根据应用-开发配置-openid配置选择支持的字段。
            // model.BuyerId = "2088102146225135";

            // 设置买家支付宝用户唯一标识
            model.BuyerOpenId = data.OpenId;


            // 设置商户门店编号
            model.StoreId = "NJ_001";


            //SignParams agreementSignParams = new SignParams();
            //agreementSignParams.SignNotifyUrl = parm.NotifyUrl;
            //model.AgreementSignParams = agreementSignParams;

            request.SetBizModel(model);
            // 第三方代调用模式下请设置app_auth_token
            // request.PutOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

            AlipayTradeCreateResponse response = alipayClient.Execute(request);

            if (!response.IsError)
            {
                Console.WriteLine("调用成功");
            }
            else
            {
                Console.WriteLine("调用失败");
            }
            return response;
        }

        private static AlipayConfig GetAlipayConfig(ConstDto parm)
        {
            string privateKey = parm.privateKey;
            string alipayPublicKey = parm.alipayPublicKey;
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.ServerUrl = "https://openapi.alipay.com/gateway.do";
            alipayConfig.AppId = parm.AppId;

            alipayConfig.PrivateKey = privateKey;
            alipayConfig.Format = "json";
            alipayConfig.AlipayPublicKey = alipayPublicKey;
            alipayConfig.Charset = parm.Charset;
            alipayConfig.SignType = parm.SignType;
            return alipayConfig;
        }
    }
}
View Code

支付Model相关

public class AlipayTradeDto
    { 
        /// <summary>
        /// 小程序APPID
        /// </summary>
        public string AppId { get; set; }
        /// <summary>
        /// 总金额
        /// </summary>
        public string TotalAmount { get; set; }
        /// <summary>
        /// 折扣金额
        /// </summary>
        public string DiscountAmount { get { return GetDiscountAmount(); } }
        public string OpenId { get; set; }
        /// <summary>
        /// 是否打折 不传不打折  1 打折
        /// </summary>
        public int? Discountable { get; set; }
        /// <summary>
        /// 打八折 就传值8  不传不打折  传值较小 打骨折
        /// </summary>
        public int? Discount { get; set; }

        private string GetDiscountAmount()
        {
            var DiscountAmount = this.TotalAmount;
            if (Discountable.HasValue&& Discountable.Value == 1&& Discount.HasValue&& Discount.Value>0&&Discount.Value<10)
            {
                DiscountAmount = (Convert.ToDouble(TotalAmount) * Discount.Value).ToString("0.00");
            }
            return DiscountAmount;
        }


    }

    public class ConstDto
    {
        /// <summary>
        /// 应用公钥
        /// </summary>
        public string publicKey { get; set; }
        /// <summary>
        /// 应用私钥
        /// </summary>
        public string privateKey { get; set; }
        /// <summary>
        /// 支付宝公钥
        /// </summary>
        public string alipayPublicKey { get; set; }
        /// <summary>
        /// 支付宝小晨曦APPId
        /// </summary>
        public string AppId { get; set; }
        /// <summary>
        /// AES秘钥
        /// </summary>
        public string AesKey = "LnmGMYjhVxy2sJz5miL9JQ==";

        public string NotifyUrl { get; set; }

        public string Charset { get; set; }
        public string SignType { get; set; }
    }

    public class AlipayConst
    {
        public static ConstDto GetAliPayConst(string appid)
        {
            ConstDto dto = new ConstDto();
            ///充电宝小程序
            if (appid== "202xxxxx040")
            {
                dto.privateKey= "MII。。。";

                dto.alipayPublicKey = "MII。。。";

                dto.publicKey = "MII。。。";

                dto.AppId = "2022022222222222xxx";//
                dto.Charset = "UTF-8";
                dto.SignType = "RSA2";
                dto.NotifyUrl = "https://xxx.com/swapAlipay/api/v1/Revice/AliPayNotify";
                return dto;
            }
            return null;
        } 
         
    }

@天才卧龙

标签:string,get,C#,id,支付,using,model,NeCore3.1,public
From: https://www.cnblogs.com/chenwolong/p/18574870

相关文章

  • leetcode1109. 航班预订统计
    1109.航班预订统计这道题使用暴力解法,如果数据比较多,first和second跨度比较大时会超时。比如下面这个暴力解:classSolution{public:vector<int>corpFlightBookings(vector<vector<int>>&bookings,intn){vector<int>res(n,0);intsize=boo......
  • 【VMware VCF】基于 RDU 方式更新 VCF 环境中的 vCenter Server 组件。
    ReducedDowntimeUpgrade(RDU)是一种基于“迁移”的vCenterServer更新方式,通过临时部署一个与源vCenterServer完全一致的目标vCenterServer(类似于跨版本vCenterServer升级),然后找一个维护窗口期完成源vCenterServer和目标vCenterServer的切换即可,由于使用RDU更新......
  • 6.C语言函数(下)
    文章目录六、数组做函数参数七、嵌套调用和链式访问7.1嵌套调用7.2链式访问八、函数的声明和定义8.1单个文件8.2多个文件(重要)!!8.3static和extern8.3.1static修饰局部变量8.3.2static修饰全局变量8.3.3static修饰函数六、数组做函数参数在使用函数解决问......
  • 【C++动态规划 贪心】3180. 执行操作可获得的最大总奖励 I|1848
    本文涉及知识点C++贪心C++动态规划LeetCode3180.执行操作可获得的最大总奖励I给你一个整数数组rewardValues,长度为n,代表奖励的值。最初,你的总奖励x为0,所有下标都是未标记的。你可以执行以下操作任意次:从区间[0,n-1]中选择一个未标记的下标i。如果......
  • C++_内存模型和包
    C++内存堆(heap)和栈(stack)是两种用于存储数据的内存区域 stack栈内存是由操作系统自动管理栈是一种用于存储局部变量和函数调用信息的内存区域,通常采用LIFO(后进先出)结构。 heap堆内存是用于动态分配的内存区域,通过显式地使用new和delete C语言【malloc分配空间,free......
  • rustdesk中继服务器的docker镜像使用-有手就行
    rustdesk中继服务器搭建踩坑文章目录前言一、官方文档二、使用的配置三、docker拉取并运行1、docker拉取镜像2、运行hbbs3、运行hbbr四、配置防火墙与安全组1、配置防火墙2、安全组配置3、测试网络连通性五、在客户端设置hbbs/hbbr地址1、点击ID......
  • c#中的委托
    委托:delegate与类平级用于封装,解耦//声明一个委托delegatevoidFunc(intx);简单使用namespaceConsoleApp2;classProgram{/***委托*/publicdelegatedoubleCalculateFunction(doublex,doubley);/***加法*/......
  • 九、Spring Boot集成Spring Security之授权概述
    目录前言一、授权概述二、用户权限三、用户授权流程三、SpringSecurity授权方式1、请求级别授权2、方法级别授权前言本文介绍什么是授权,SpringSecurity的授权配置有哪些,配合以下内容观看效果更佳!!!什么是授权,授权有哪些流程,SpringSecurity的授权配置有几种?请查看九、SpringB......
  • 《DNK210使用指南 -CanMV版 V1.0》第四十章 YOLO2人手检测实验
    第四十章YOLO2人手检测实验1)实验平台:正点原子DNK210开发板2)章节摘自【正点原子】DNK210使用指南-CanMV版V1.03)购买链接:https://detail.tmall.com/item.htm?&id=7828013987504)全套实验源码+手册+视频下载地址:http://www.openedv.com/docs/boards/k210/ATK-DNK210.html5)正......
  • Thinkpad X1 Tablet gen2 键盘固件逆向分析实现Ctrl与Fn换位
    0.折腾原因一直想有一个键盘+红点+触摸板的桌面组合放在办公室用。键盘+红点操作效率高,触摸板在看文档网页时翻页顺滑。几经转折发现了ThinkpadX1Tabletgen2原装键盘,除了太薄手感一般之外,完美满足需求,而且这款键盘折叠部分里的排线很容易折断,导致价格非常便宜,很适合用来改装US......