C#实现微信扫码支付

第一步:获取AppID AppSecret(去微信公众平台申请网址https://mp.weixin.qq.com/)
第二步:下载微信支付demo WxPayAPI,其中两个包business,lib,添加到项目中。
第三步:lib包中的有一个类文件config.cs有几个基础参数的要设置,这几个appid,mchid,key,APPSECRET,是在你申请通过微信支付接口后获取的。代码贴上来

using System;
using System.Collections.Generic;
using System.Web;
using WxPayAPI;
namespace WxPayAPI
{
    /**
    * 	配置账号信息
    */
    public class WxPayConfig
    {
        //=======【基本信息设置】=====================================
        /* 微信公众号信息配置
        * APPID:绑定支付的APPID(必须配置)
        * MCHID:商户号(必须配置)
        * KEY:商户支付密钥,参考开户邮件设置(必须配置)
        * APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置)
        */
        public const string APPID = "yourAPPID";
        public const string MCHID = "yourMCHID";
        public const string KEY = "yourKEY";
        public const string APPSECRET = "yourAPPSECRET";
        //操作密码:$$$csq5138553
        //=======【证书路径设置】===================================== 
        /* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要)
        */
        public const string SSLCERT_PATH = "cert/apiclient_cert.p12";
        public const string SSLCERT_PASSWORD = "1504105221";



        //=======【支付结果通知url】===================================== 
        /* 支付结果通知回调url,用于商户接收支付结果
        */
        public const string NOTIFY_URL = "你的回调url的地址用来接收支付完成后的操作";

        //=======【商户系统后台机器IP】===================================== 
        /* 此参数可手动配置也可在程序中自动获取
        */
        public const string IP = "8.8.8.8";


        //=======【代理服务器设置】===================================
        /* 默认IP和端口号分别为0.0.0.0和0,此时不开启代理(如有需要才设置)
        */
        public const string PROXY_URL = "http://10.152.18.220:8080";

        //=======【上报信息配置】===================================
        /* 测速上报等级,0.关闭上报; 1.仅错误时上报; 2.全量上报
        */
        public const int REPORT_LEVENL = 1;

        //=======【日志级别】===================================
        /* 日志等级,0.不输出日志;1.只输出错误信息; 2.输出错误和正常信息; 3.输出错误信息、正常信息和调试信息
        */
        public const int LOG_LEVENL = 0;
    }
}

第四步:获取微信扫码支付二维码

前台
 <!-- payment 支付方式选择 -->
        <div class="payment">
            <!-- 微信支付 -->
            <div class="pay-weixin">
                <div class="p-w-hd">微信支付</div>
                <div class="p-w-bd" style="position:relative">
                    <div class="j_weixinInfo" style="position:absolute; top: -36px; left: 130px;"></div>
                    <div class="p-w-box">
                        <div class="pw-box-hd">
                            <asp:Image ID="Image2" runat="server" style="width:298px;height:298px;"/>
                         <div id="ly" class="pw-box-hd" style="position:absolute; top:0; left:130px; z-index:2;background:#f5f5f5; filter:alpha(opacity=70); opacity:0.7;display: none;"> 
                        </div>
                        </div>

                        <div class="pw-retry j_weixiRetry" style="display: none;">
                            <a class="ui-button ui-button-gray j_weixiRetryButton" href="javascript:getWeixinImage2();">获取失败 点击重新获取二维码  </a>
                        </div>
                        <div class="pw-box-ft">
                            <p>请使用微信扫一扫</p>
                            <p>扫描二维码支付</p>
                        </div>
                    </div>
                    <div class="p-w-sidebar"><%--<img src="images/logo/20180515161457.png" />--%></div>
                </div>
            </div>
            <!-- 微信支付 end -->
            <!-- payment-change 变更支付方式 -->
            <div class="payment-change">
                <a class="pc-wrap" onclick="window.history.go(-1)">
                    <i class="pc-w-arrow-left">&lt;</i>
                    <strong>选择其他支付方式</strong>
                </a>
            </div>
            <!-- payment-change 变更支付方式 end -->
        </div>
        <!-- payment 支付方式选择 end -->
        后台:
         string ordersId = Request.QueryString["ordersId"];
            
            
            Handler handler = new Handler();
            string sumMoney = handler.GetSumMoneyByOrderId(ordersId);

            if (!String.IsNullOrEmpty(sumMoney))
            {
                this.Label1.Text = ordersId;
                this.Label2.Text = sumMoney;
                this.hidOrderId.Value = ordersId;
                sumMoney = sumMoney + "00";
                string text = "食色者-订单编号" + ordersId;
                Log.Info(this.GetType().ToString(), "page load");
                NativePay nativePay = new NativePay();

                //生成扫码支付模式一url
                //string url1 = nativePay.GetPrePayUrl("123456789");

                //生成扫码支付模式二url
                try
                {


                    string url2 = nativePay.GetPayUrl(ordersId, text, sumMoney);

                    //将url生成二维码图片
                    Image2.ImageUrl = "MakeQRCode.aspx?data=" + HttpUtility.UrlEncode(url2);
                }
                catch
                {

                    Response.Redirect("Reminder-zfError.html");
                }
            }
            else
            {
                Response.Redirect("Reminder-zfError.html");
            }

第五步:回调url地址里的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WxPayAPI;

public partial class PaymentCallback_ResultNotifyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ResultNotify resultNotify = new ResultNotify(this);
        resultNotify.ProcessNotify();
    }  
}

第六步:business文件夹里有一个叫ResultNotify.cs的文件里获取支付结果:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WxPayAPI
{
    /// <summary>
    /// 支付结果通知回调处理类
    /// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证,将验证结果反馈给微信支付后台
    /// </summary>
    public class ResultNotify:Notify
    {
        public ResultNotify(Page page):base(page)
        {
        }

        public override void ProcessNotify()
        {
            WxPayData notifyData = GetNotifyData();

            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            string transaction_id = notifyData.GetValue("transaction_id").ToString();

            //查询订单,判断订单真实性
            if (!QueryOrder(transaction_id))
            {
                //若订单查询失败,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }
            //查询订单成功
            else
            {
               //到这里说明已经支付成功了,然后调用数据库把这条订单改为已经支付。
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }
        }

        //查询订单
        private bool QueryOrder(string transaction_id)
        {
            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

到这里所有扫码支付就完成了。我是在支付完成后,在扫码支付页面也就是第四步获取扫码支付二维码的那个页面,做了一个ajax不间断3秒调用数据库,如果数据库已经支付了,就直接跳转到支付成功提示页面。

<script type="text/JavaScript">
    var timeer;
    $(document).ready(function () {
        if ($("#hidOrderId").val() != '') {
            //alert("调用ajax");
            timeer = setInterval("GetStatus()", 3000);
        }
    });
    function GetStatus() {
        var orderId = $("#hidOrderId").val();
        $.ajax({
            url: "yourajaxpage.html",
            type: "post",
            dataType: "json",
            data: {
                method: "yourmethod",
                orderId: orderId
            },
            success: function (data) {
                if (data.status == '1') {

                        window.location.href = "zfOk-" + orderId + ".html"; //页面跳转
                    
                }else
                {
                   window.location.href = "zfError.html"; //页面跳转
				 }

            }
        });
    }
    </script>

以上代码就可以实现微信扫码登录
演示网址(https://www.shisezhe.com/shoppingCart.html,点击里面的微信支付就可以到微信扫码支付页面,如果有不明白的可以评论

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值