欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于微信个人收款码的支付接口的实现与源码

程序员文章站 2022-05-01 20:24:17
前言 如果我们希望为自己的网站增添微信扫码收款功能,用于收取一些服务费用,为个人网站提供自动化有偿服务的话,那我们有哪些方案呢? ​首先,我们先看下效果,以下是服务端的收款二维码的发起示例演示: 其次,我们再看看手机端 微信扫码支付的演示: 我们手机端会将收款的消息推送到服务器API。其中接口信息定 ......
前言
如果我们希望为自己的网站增添微信扫码收款功能,用于收取一些服务费用,为个人网站提供自动化有偿服务的话,那我们有哪些方案呢?

​首先,我们先看下效果,以下是服务端的收款二维码的发起示例演示:

其次,我们再看看手机端 微信扫码支付的演示:

我们手机端会将收款的消息推送到服务器api。其中接口信息定义大概如下:

{"title":"微信支付","time":"2020-05-08 23:34:11","money":"0.80","deviceid":"mydevice","content":"[2条]微信支付: 微信支付收款0.80元(朋友到店)"} 

以上视频是让大家有个效果感观,下面我们将详细讲解具体实现原理与细节。

 

如果您对本专题有兴趣,可以按照下面的思路实现。

同时,您也可以在 文章结尾处 查看获取源码的方法 供用于学习研究用途的 完整源码zip

源码zip包括:

一、主源码-服务端api (基于.net core webapi,用于处理支付逻辑)

二、前端基于boostrap的发起二维码扫码界面ui

三、android apk 源码 (java,用于监控手机消息)

四、apk (编译完成可用的apk, 如果你不熟悉android,可以直接用这个已经编译好的apk )

 

api处理源码示例如下,

using system;
using system.linq;
using system.linq.expressions;
using system.collections.generic;
using microsoft.aspnetcore.mvc;
using microsoft.aspnetcore.authorization;
using lyn.pay.api.domain;
using lyn.pay.api.utils;
using lyn.pay.api.dal;

namespace lyn.pay.api.controllers
{
    /// <summary>
    /// 控制器
    /// </summary>
    [route("v1/[controller]/[action]")]
    public class paycontroller : controller
    {
        //https://github.com/stulzq/snowflake-net
        private static snowflake.core.idworker worker = new snowflake.core.idworker(1, 1);

        public paycontroller()
        {

        }

        #region 业务应用
        [httppost]
        [allowanonymous]
        public jsonresult queryalreadybuy([frombody]addordervo vo)
        {
            var remoteuserip = httpcontext.connection.remoteipaddress.maptoipv4().tostring();
            var userip = vo.ip.hasvalue() ? vo.ip : remoteuserip;

            //检查这个ip是否已经购买过此文章了
            var alreadybuy = service.queryany("select 1 from [order]  d where d.tradeproduct = @tradeproduct and d.ip = @ip and d.tradestatus=1 ", new { tradeproduct = vo.productname, ip = userip });
            if (alreadybuy)
            {
                return json(result.fail(resultcode.alreadybuy));
            }
            else
            {
                return json(result.fail(resultcode.fail));
            }
        }

        /// <summary>
        /// 产生新支付订单
        /// </summary>
        /// <param name="vo">订单</param>
        /// <returns>列表数据</returns>
        [httppost]
        [allowanonymous]
        public jsonresult addorder([frombody]addordervo vo)
        {
            var remoteuserip = httpcontext.connection.remoteipaddress.maptoipv4().tostring();
            var userip = vo.ip.hasvalue() ? vo.ip : remoteuserip;

            //检查这个ip是否已经购买过此文章了
            var alreadybuy = service.queryany("select 1 from [order]  d where d.tradeproduct = @tradeproduct and d.ip = @ip and d.tradestatus=1 ", new { tradeproduct = vo.productname, ip = userip });
            if (alreadybuy)
            {
                return json(result.fail(resultcode.alreadybuy));
            }

            var money = 0;
            var sqlgetvalidmoney = @"
                                    select  top 1 * from product p where (p.[name]=@productname  or p.[name]='gobal') and  not exists(
                                        select 1 from [order] d where (d.tradeproduct = p.[name] or p.[name]='gobal') and d.trademoney = p.money and d.tradestatus=0
                                    )  order by p.isgobal asc , p.money asc
                                    ";
            var r = new order();
            //先将过期的更新为过期状态
            service.execute("update [order] set tradestatus=3,modifytime=getdate() where tradestatus=0 and datediff(ss,createtime,getdate())>120", null);

            var p = service.querysingle<product>(sqlgetvalidmoney, new { productname = vo.productname });
            if (p != null)
            {

                r.id = worker.nextid();
                long.tryparse(r.id.tostring().substring(1), out long shortid);
                r.id = shortid;

                r.tradeno = r.id.tostring();// vo.tradeno;
                r.tradeproduct = vo.productname;
                r.trademoney = p.money;
                r.tradestatus = 0;
                r.remark = remoteuserip;
                r.ip = userip;
                r.city = vo.city;
                r.createtime = datetime.now;
                service.execute("insert into [order](id,tradeno,tradeproduct,trademoney,remark,ip,city,tradestatus,createtime)values(@id,@tradeno,@tradeproduct,@trademoney,@remark,@ip,@city,@tradestatus,@createtime)"
                    , new { id = r.id, tradeno = r.tradeno, tradeproduct = r.tradeproduct, trademoney = r.trademoney, remark = r.remark, ip = r.ip, city = r.city, tradestatus = r.tradestatus, createtime = r.createtime });
                money = p.money;
            }

            if (money > 0)
            {
                return json(result.success(new { tradeno = r.id, money = money , moneyyuan = money/100.0, payqrcode = $"/payqrcode/{money}.jpg" }));
            }
            else
            {
                return json(result.fail(resultcode.fail));
            }
        }

        /// <summary>
        /// 产生新支付订单
        /// </summary>
        /// <param name="vo">订单</param>
        /// <returns>列表数据</returns>
        [httppost]
        [allowanonymous]
        public jsonresult discardorder([frombody]discardordervo vo)
        {
            //先将过期的更新为过期状态
            service.execute("update [order] set tradestatus=3,modifytime=getdate() where tradestatus=0 and datediff(ss,createtime,getdate())>120", null);

            var d = service.querysingle<order>("select * from [order] where tradeno = @tradeno", new { tradeno = vo.tradeno });
            if (d != null && d.tradestatus == 0)
            {
                service.execute("update [order] set tradestatus=2,modifytime=getdate() where tradestatus=0 and  tradeno = @tradeno", new { tradeno = vo.tradeno });
                return json(result.success());
            }
            return json(result.fail());
        }

        /// <summary>
        /// 查询订单
        /// </summary>
        /// <param name="vo">订单</param>
        /// <returns>列表数据</returns>
        [httppost]
        [allowanonymous]
        public jsonresult queryorder([frombody]discardordervo vo)
        {
            var d = service.querysingle<order>("select * from [order] where tradeno = @tradeno", new { tradeno = vo.tradeno });
            if (d != null && d.tradestatus == 1)
            {
                return json(result.success());
            }
            return json(result.fail());
        }


        [httppost]
        [allowanonymous]
        public jsonresult paynotify([frombody]paynotifyvo vo)
        {
            if (vo.title.indexof("微信支付")>=0 && vo.money.hasvalue())
            {
                //{"title":"微信支付","time":"2019-06-19 21:45:23","money":"0.10","encrypt":"0","deviceid":"ffffffff-c818-83fb-ffff-ffffbbd87511","content":"微信支付收款0.10元(朋友到店)"}
                var moneyfen = convert.toint32(decimal.parse(vo.money) * 100);
                service.execute("update [order] set tradestatus=1,modifytime=getdate() where tradestatus=0 and  trademoney = @trademoney", new { trademoney = moneyfen });
            }
            if (vo.title.indexof("微信收款助手")>=0)
            {
                //{ "title":"微信收款助手","time":"2019-06-20 22:24:54","money":"null","deviceid":"ffffffff-c818-83fb-ffff-ffffbbd87511","content":"[店员消息]收款到账0.01元"}
                var content = vo.content;
                var money = content.substring(content.indexof("收款到账"), content.indexof("元") - content.indexof("收款到账")).replace("收款到账", "");

                var moneyfen = convert.toint32(decimal.parse(money) * 100);
                service.execute("update [order] set tradestatus=1,modifytime=getdate() where tradestatus=0 and  trademoney = @trademoney", new { trademoney = moneyfen });
            }

            return json(result.success());
        }

        #endregion
    }
}

 

下图是支付回调的发起与结果的接收示例:

基于微信个人收款码的支付接口的实现与源码

细节原理请仔细往下看.....

 

作为一名程序员,我们或多或少都希望建立自己的个人技术网站、技术博客等等,用于记录自己的汗水点滴。

基于微信个人收款码的支付接口的实现与源码

同时,如果我们希望为自己的网站增添微信扫码收款功能,用于收取一些服务费用,为个人网站提供自动化有偿服务的话,那我们有哪些方案呢?

 

一、注册公司,在微信公众平台申请支付权限

二、通过微信个人收款码实现个人收款接口

 

本文我们分析第二种方法,通过微信个人收款码实现个人收款接口。

这种方法的实现成本非常低,但也只是适用于一些个人网站,小并发量的收款服务,当然了,如果你的网站有大量用户向你支付,你还不主动去申请注册公司么。

 

言归正传,哪么怎么实现收款接口呢?

首先,我们看一个演示示例: 

可复制链接打开体验 http://letyouknow.net/serverfarm/serverfarm-tutorial3.html

此示例是技术文章内容付费示例,用户试读部分后,点击 展开阅读更多 并且扫码支付成功后,展示全部内容。

 

首先,我们需要制作出一套专业的ui,用于展示收款码

一、当我们点击展开阅读更多按钮后,我们需要显示一获取二维码的示意图

基于微信个人收款码的支付接口的实现与源码

 

二、根据预设的资费情况,从后台拉取对应的个人收款二维码,并设置收款码有效期,此示例默认2分钟。

基于微信个人收款码的支付接口的实现与源码

三、设置超时失效机制,引导重新发起支付

基于微信个人收款码的支付接口的实现与源码

 

四、预设个人收款二维码 

      我们需要将同一个金额照不同的收款备注或不同的金额尾数设置多个,然后保存到服务端,由前端ui的产品拉取对应的金额的二维码图片,显示给用户

 

五、微信收款通知 回调服务器api

        我们可以用android apk 用于监控收款通知,并实时回调我们的服务器,修改用户订单的支付状态。

        我们将apk安装在手机上后,当有用户扫码付款后,我们的微信app便收到收款通知,同时,我们回调服务器。

 

基于微信个人收款码的支付接口的实现与源码

 

此方案特性:

这种实现办法适合小额,支付频率不高的场景。比如针对 1元这个金额生成了100个有不同收款备注信息的二维码,那么也就是说5分钟内最多只能有100个人同时支付,1分钟内20个同时支付。对于一些小网站可以满足需求。

 

此方案的核心是设计思想,另外就是我们如何实时获取到收款通知。我们用android apk 用于监控收款通知,并实时回调我们的服务器,修改用户订单的支付状态。有关实时获取收款通知的实现方法,我们后续将另起一个篇章重点介绍。

 

六、接口定义示例

{"title":"微信支付","time":"2020-05-08 23:34:11","money":"0.80","deviceid":"mydevice","content":"[2条]微信支付: 微信支付收款0.80元(朋友到店)"} 

 

七、api源码的说明

       下载源码后,用vs2017or2019打开项目,f5运行即可,
  http://localhost:54914/demo.html

  

using system;
using system.linq;
using system.linq.expressions;
using system.collections.generic;
using microsoft.aspnetcore.mvc;
using microsoft.aspnetcore.authorization;
using lyn.pay.api.domain;
using lyn.pay.api.utils;
using lyn.pay.api.dal;

namespace lyn.pay.api.controllers
{
    /// <summary>
    /// 控制器
    /// </summary>
    [route("v1/[controller]/[action]")]
    public class paycontroller : controller
    {
        //https://github.com/stulzq/snowflake-net
        private static snowflake.core.idworker worker = new snowflake.core.idworker(1, 1);

        public paycontroller()
        {

        }

        #region 业务应用
        [httppost]
        [allowanonymous]
        public jsonresult queryalreadybuy([frombody]addordervo vo)
        {
            var remoteuserip = httpcontext.connection.remoteipaddress.maptoipv4().tostring();
            var userip = vo.ip.hasvalue() ? vo.ip : remoteuserip;

            //检查这个ip是否已经购买过此文章了
            var alreadybuy = service.queryany("select 1 from [order]  d where d.tradeproduct = @tradeproduct and d.ip = @ip and d.tradestatus=1 ", new { tradeproduct = vo.productname, ip = userip });
            if (alreadybuy)
            {
                return json(result.fail(resultcode.alreadybuy));
            }
            else
            {
                return json(result.fail(resultcode.fail));
            }
        }

        /// <summary>
        /// 产生新支付订单
        /// </summary>
        /// <param name="vo">订单</param>
        /// <returns>列表数据</returns>
        [httppost]
        [allowanonymous]
        public jsonresult addorder([frombody]addordervo vo)
        {
            var remoteuserip = httpcontext.connection.remoteipaddress.maptoipv4().tostring();
            var userip = vo.ip.hasvalue() ? vo.ip : remoteuserip;

            //检查这个ip是否已经购买过此文章了
            var alreadybuy = service.queryany("select 1 from [order]  d where d.tradeproduct = @tradeproduct and d.ip = @ip and d.tradestatus=1 ", new { tradeproduct = vo.productname, ip = userip });
            if (alreadybuy)
            {
                return json(result.fail(resultcode.alreadybuy));
            }

            var money = 0;
            var sqlgetvalidmoney = @"
                                    select  top 1 * from product p where (p.[name]=@productname  or p.[name]='gobal') and  not exists(
                                        select 1 from [order] d where (d.tradeproduct = p.[name] or p.[name]='gobal') and d.trademoney = p.money and d.tradestatus=0
                                    )  order by p.isgobal asc , p.money asc
                                    ";
            var r = new order();
            //先将过期的更新为过期状态
            service.execute("update [order] set tradestatus=3,modifytime=getdate() where tradestatus=0 and datediff(ss,createtime,getdate())>120", null);

            var p = service.querysingle<product>(sqlgetvalidmoney, new { productname = vo.productname });
            if (p != null)
            {

                r.id = worker.nextid();
                long.tryparse(r.id.tostring().substring(1), out long shortid);
                r.id = shortid;

                r.tradeno = r.id.tostring();// vo.tradeno;
                r.tradeproduct = vo.productname;
                r.trademoney = p.money;
                r.tradestatus = 0;
                r.remark = remoteuserip;
                r.ip = userip;
                r.city = vo.city;
                r.createtime = datetime.now;
                service.execute("insert into [order](id,tradeno,tradeproduct,trademoney,remark,ip,city,tradestatus,createtime)values(@id,@tradeno,@tradeproduct,@trademoney,@remark,@ip,@city,@tradestatus,@createtime)"
                    , new { id = r.id, tradeno = r.tradeno, tradeproduct = r.tradeproduct, trademoney = r.trademoney, remark = r.remark, ip = r.ip, city = r.city, tradestatus = r.tradestatus, createtime = r.createtime });
                money = p.money;
            }

            if (money > 0)
            {
                return json(result.success(new { tradeno = r.id, money = money , moneyyuan = money/100.0, payqrcode = $"/payqrcode/{money}.jpg" }));
            }
            else
            {
                return json(result.fail(resultcode.fail));
            }
        }

        /// <summary>
        /// 产生新支付订单
        /// </summary>
        /// <param name="vo">订单</param>
        /// <returns>列表数据</returns>
        [httppost]
        [allowanonymous]
        public jsonresult discardorder([frombody]discardordervo vo)
        {
            //先将过期的更新为过期状态
            service.execute("update [order] set tradestatus=3,modifytime=getdate() where tradestatus=0 and datediff(ss,createtime,getdate())>120", null);

            var d = service.querysingle<order>("select * from [order] where tradeno = @tradeno", new { tradeno = vo.tradeno });
            if (d != null && d.tradestatus == 0)
            {
                service.execute("update [order] set tradestatus=2,modifytime=getdate() where tradestatus=0 and  tradeno = @tradeno", new { tradeno = vo.tradeno });
                return json(result.success());
            }
            return json(result.fail());
        }

        /// <summary>
        /// 查询订单
        /// </summary>
        /// <param name="vo">订单</param>
        /// <returns>列表数据</returns>
        [httppost]
        [allowanonymous]
        public jsonresult queryorder([frombody]discardordervo vo)
        {
            var d = service.querysingle<order>("select * from [order] where tradeno = @tradeno", new { tradeno = vo.tradeno });
            if (d != null && d.tradestatus == 1)
            {
                return json(result.success());
            }
            return json(result.fail());
        }


        [httppost]
        [allowanonymous]
        public jsonresult paynotify([frombody]paynotifyvo vo)
        {
            if (vo.title.indexof("微信支付")>=0 && vo.money.hasvalue())
            {
                //{"title":"微信支付","time":"2019-06-19 21:45:23","money":"0.10","encrypt":"0","deviceid":"ffffffff-c818-83fb-ffff-ffffbbd87511","content":"微信支付收款0.10元(朋友到店)"}
                var moneyfen = convert.toint32(decimal.parse(vo.money) * 100);
                service.execute("update [order] set tradestatus=1,modifytime=getdate() where tradestatus=0 and  trademoney = @trademoney", new { trademoney = moneyfen });
            }
            if (vo.title.indexof("微信收款助手")>=0)
            {
                //{ "title":"微信收款助手","time":"2019-06-20 22:24:54","money":"null","deviceid":"ffffffff-c818-83fb-ffff-ffffbbd87511","content":"[店员消息]收款到账0.01元"}
                var content = vo.content;
                var money = content.substring(content.indexof("收款到账"), content.indexof("元") - content.indexof("收款到账")).replace("收款到账", "");

                var moneyfen = convert.toint32(decimal.parse(money) * 100);
                service.execute("update [order] set tradestatus=1,modifytime=getdate() where tradestatus=0 and  trademoney = @trademoney", new { trademoney = moneyfen });
            }

            return json(result.success());
        }

        #endregion
    }
}

  

八、源码zip仅供用于学习与研究用途

一、主源码-服务端api (基于.net core webapi,用于处理支付逻辑)

二、前端基于boostrap的发起二维码扫码界面ui

三、android apk 源码 (java,用于监控手机消息)

四、apk (编译完成可用的apk, 如果你不熟悉android,可以直接用这个已经编译好的apk )

 

九、如何获取源码?

      扫码关注的dotnet框架学苑公众号,直接在公众号文章中付费阅读对应的文章,文章尾部有源码压缩包。 

 基于微信个人收款码的支付接口的实现与源码