支付宝API

//充值页面
<div class="rule userinfo" id="ruleB" runat="server" style="padding-top: 20px;">
                    <section class="article-list" style="padding-top: 0">
                        <h4>在线充值</h4>
                        <div class="list form">
                            <div class="zf">
                                <code id="Money1">充值金额:</code>
                                <asp:TextBox ID="txtMoney" runat="server" style="color:red;font-weight:bold;" Enabled="false"></asp:TextBox>
                                <asp:Button ID="BtnSave" CssClass="submitbt" Text="提交" OnClientClick="return CheckData();" OnClick="BtnSave_Clikc" runat="server" />
                                <p class="tips tips1 clearfix"><span id="ClearDetail">说明:手续费为充值金额的</span><asp:Label ID="lblField12" runat="server"></asp:Label>
                                    %;<br />
                                    实际到账金额=充值金额-手续费<br />
                                    在线充值成功后请不要立即关闭支付宝的充值成功提示页面,点击返回商家或等待页面自动返回。如充值成功但未到账请联系客服!</p>
                            </div>
                        </div>
                        <div class="link">
                            <a href="Account.aspx">返回 >></a>
                        </div>
                    </section>
                </div>
<pre name="code" class="csharp">//充值页面后台
private void AlipaySend(string TypeId)
    {
        //支付类型
        string payment_type = "1";
        //服务器异步通知页面路径
        //string Local = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string notify_url = sc.GetHost() + "/User/ZFBReturnUrl.aspx";
        string return_url = sc.GetHost() + "/User/ZFBReturnUrl.aspx";
        DataSet ds = GetCorporateAct(TypeId);
        if (ds == null || ds.Tables[0].Rows.Count == 0)
        {
            return;
        }
        //支付宝收款账号
        string seller_email = ds.Tables[0].Rows[0]["Field13"].ToString();
        string partner = ds.Tables[0].Rows[0]["Field14"].ToString();
        Random R = new Random();
        string strOrderNo = "G" + DateTime.Now.ToString("yyyyMMddHHmmss") + R.Next(1000, 9999).ToString();
        //编码
        string Input_charset = "utf-8";
        //商户订单号
        string out_trade_no = strOrderNo;

        //订单名称
        string subject = "充值";

        //付款金额
        //再次验证充值金额
        try
        {
            float t_fee = Convert.ToSingle(txtMoney.Text);
        }
        catch
        {
            return;
        }
        string total_fee = txtMoney.Text;

        //订单描述
        string body = "充值";

        //把请求参数打包成数组
        SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
        sParaTemp.Add("partner", partner);
        sParaTemp.Add("_input_charset", Input_charset);
        sParaTemp.Add("service", "create_direct_pay_by_user");
        sParaTemp.Add("payment_type", payment_type);
        sParaTemp.Add("notify_url", notify_url);
        sParaTemp.Add("return_url", return_url);
        sParaTemp.Add("seller_email", seller_email);
        sParaTemp.Add("out_trade_no", out_trade_no);
        sParaTemp.Add("subject", subject);
        sParaTemp.Add("total_fee", total_fee);
        sParaTemp.Add("body", body);
        //建立请求
        string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");
        Response.Write(sHtmlText);
    }
    }


 
//充值成功后回发页面
<pre name="code" class="html"><%@ Page Language="C#" AutoEventWireup="true" CodeFile="ZFBReturnUrl.aspx.cs" Inherits="User_ZFBReturnUrl" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>支付宝充值</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>


 
//回发页面后台
<pre name="code" class="csharp"><pre name="code" class="csharp"><pre name="code" class="csharp">using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Com.Alipay;
using BLL;
using System.Collections.Generic;
using System.Collections.Specialized;
using Common;

public partial class User_ZFBReturnUrl : System.Web.UI.Page
{
    DataBase db = new DataBase(); C_CommonOpt c_c = new C_CommonOpt();
    STLBCommon sc = new STLBCommon();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["LoginName"] == null)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请重新登录!');parent.location='" + sc.GetHost() + "/Default.aspx'</script>");
            return;
        }

        SortedDictionary<string, string> sPara = GetRequestPost();
        if (sPara.Count > 0)//判断是否有带返回参数
        {
            Notify aliNotify = new Notify();
            bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);
            if (verifyResult)//验证成功
            {
                /
                //请在这里加上商户的业务逻辑程序代码
                //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
                //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表

                //商户订单号
                //string out_trade_no = Request.Form["out_trade_no"];

                //支付宝交易号
                string trade_no = Request.QueryString["trade_no"];

                //交易状态
                string trade_status = Request.QueryString["trade_status"];

                //用户ID
                string UserName = "";
                if (Session["LoginName"] != null)
                {
                    UserName = GetCusCode();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请重新登录!');parent.location='" + sc.GetHost() + "/Default.aspx'</script>");
                    return;
                }

                //string UserName = "80001";

                C_Base_StyleInfo C_B = new C_Base_StyleInfo();
                decimal DRate = 0;
                DataSet Rateds = C_B.GetList(1, " Style='15' and void_flag='0' and ShortName like '%支付宝%'", "");
                if (Rateds != null && Rateds.Tables.Count > 0 && Rateds.Tables[0].Rows.Count > 0)
                {
                    DRate = Convert.ToDecimal(Rateds.Tables[0].Rows[0]["Field12"]);
                }

                //交易金额
                decimal IncomMoney = Convert.ToDecimal(Request.QueryString["total_fee"]) * (1 - DRate / 100);

                string DRateFee = (Convert.ToDecimal(Request.QueryString["total_fee"]) * DRate / 100).ToString();
                string total_fee = IncomMoney.ToString();

                if (trade_status == "TRADE_SUCCESS") //该种交易状态只在一种情况下出现——开通了高级即时到账,买家付款成功后。
                {
                    //防止重复的从支付宝返回网站重复写数据
                    C_Acc_AccountDetail C_AA = new C_Acc_AccountDetail();
                    DataSet AccDs = new DataSet();
                    AccDs = C_AA.GetList(0, "bankQueue='" + trade_no + "'", "");
                    if (AccDs != null && AccDs.Tables[0].Rows.Count > 0)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>parent.location='Financial.aspx'</script>");
                        return;
                    }
                    DataTable dtsp = c_c.SelectT("select Integral_Calculate,Integral_Conversion from Sys_ParaSetup");

                    //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                    Customer C_G = new Customer();
                    DataSet ds = C_G.GetList(1, " CusCode='" + UserName + "'", "");
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        string Money = ds.Tables[0].Rows[0]["AccountMoney"].ToString();
                        Acc_Occur C_A = new Acc_Occur();
                        C_A.GFF_CustomerID = UserName;
                        C_A.IncomeMoney = total_fee;
                        C_A.Style = "1";
                        C_A.CreateUser = UserName;
                        C_A.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        C_A.Remark = "支付宝充值成功,交易号:" + trade_no;

                        //更新账户类型
                        ChangeCusType();

                        C_AA.GFF_CustomerID = UserName;
                        C_AA.Amount = total_fee;
                        C_AA.BankQueue = trade_no;
                        C_AA.OccurDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        C_AA.Rate = DRateFee;//DRate.ToString();
                        C_AA.Remark = "支付宝充值成功,交易号:" + trade_no;
                        C_AA.CreateUser = UserName;
                        C_AA.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        C_AA.Style = "1";
                        C_AA.MoneyStyle = "3";
                        C_AA.Currency = "¥";
                        
                    }
                    //success与fail及其他字符的区别在于,支付宝的服务器若遇到success时,则不再发送请求通知(即不再调用该页面,让该页面再次运行起来), 
                    //若不是success,则支付宝默认没有收到成功的信息,则会反复不停地调用该页面直到失效,有效调用时间是24小时以内。 

                    Response.Write("SUCCESS");  //请不要修改或删除
                    Response.Redirect("Financial.aspx?fid=5");
                }
                else
                {
                    Response.Write("交易失败,请核查账户金额,并联系管理员!");  //请不要修改或删除

                }
                //把返回来的充值金额充值到客户账户中 并做交易明细记录
                /
            }
            else
            {
                //验证失败
                //Response.Redirect("Financial.aspx?fid=5");
                Response.Write("网络异常,支付宝充值验证失败,请联系管理员!");
            }
        }
        else
        {
            //无参数通知
            Response.Write("交易失败,无返回参数");
        }
    }

    /// <summary>
    /// 获取支付宝POST过来通知消息,并以“参数名=参数值”的形式组成数组
    /// </summary>
    /// <returns>request回来的信息组成的数组</returns>
    public SortedDictionary<string, string> GetRequestPost()
    {
        int i = 0;
        SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
        NameValueCollection coll;
        coll = Request.QueryString;
        String[] requestItem = coll.AllKeys;

        for (i = 0; i < requestItem.Length; i++)
        {
            sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
        }
        return sArray;
    }
}

<pre name="code" class="csharp">using System.Web;
using System.Text;
using System.IO;
using System.Net;
using System;
using System.Collections.Generic;

namespace Com.Alipay
{
    /// <summary>
    /// 类名:Notify
    /// 功能:支付宝通知处理类
    /// 详细:处理支付宝各接口通知返回
    /// 版本:3.3
    /// 修改日期:2011-07-05
    /// '说明:
    /// 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
    /// 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
    /// 
    /// //注意/
    /// 调试通知返回时,可查看或改写log日志的写入TXT里的数据,来检查通知返回是否正常 
    /// </summary>
    public class Notify
    {
        #region 字段
        private string _partner = "";               //合作身份者ID
        private string _key = "";                   //商户的私钥
        private string _input_charset = "";         //编码格式
        private string _sign_type = "";             //签名方式

        //支付宝消息验证地址
        private string Https_veryfy_url = "https://mapi.alipay.com/gateway.do?service=notify_verify&";
        #endregion


        /// <summary>
        /// 构造函数
        /// 从配置文件中初始化变量
        /// </summary>
        /// <param name="inputPara">通知返回参数数组</param>
        /// <param name="notify_id">通知验证ID</param>
        public Notify()
        {
            //初始化基础配置信息
            _partner = Config.Partner.Trim();
            _key = Config.Key.Trim();
            _input_charset = Config.Input_charset.Trim().ToLower();
            _sign_type = Config.Sign_type.Trim().ToUpper();
        }

        /// <summary>
        ///  验证消息是否是支付宝发出的合法消息
        /// </summary>
        /// <param name="inputPara">通知返回参数数组</param>
        /// <param name="notify_id">通知验证ID</param>
        /// <param name="sign">支付宝生成的签名结果</param>
        /// <returns>验证结果</returns>
        public bool Verify(SortedDictionary<string, string> inputPara, string notify_id, string sign)
        {
            //获取返回时的签名验证结果
            bool isSign = GetSignVeryfy(inputPara, sign);
            //获取是否是支付宝服务器发来的请求的验证结果
            string responseTxt = "true";
            if (notify_id != null && notify_id != "") { responseTxt = GetResponseTxt(notify_id); }

            //写日志记录(若要调试,请取消下面两行注释)
            //string sWord = "responseTxt=" + responseTxt + "\n isSign=" + isSign.ToString() + "\n 返回回来的参数:" + GetPreSignStr(inputPara) + "\n ";
            //Core.LogResult(sWord);

            //判断responsetTxt是否为true,isSign是否为true
            //responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
            //isSign不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
            if (responseTxt == "true" && isSign)//验证成功
            {
                return true;
            }
            else//验证失败
            {
                return false;
            }
        }

        /// <summary>
        /// 获取待签名字符串(调试用)
        /// </summary>
        /// <param name="inputPara">通知返回参数数组</param>
        /// <returns>待签名字符串</returns>
        private string GetPreSignStr(SortedDictionary<string, string> inputPara)
        {
            Dictionary<string, string> sPara = new Dictionary<string, string>();

            //过滤空值、sign与sign_type参数
            sPara = Core.FilterPara(inputPara);

            //获取待签名字符串
            string preSignStr = Core.CreateLinkString(sPara);

            return preSignStr;
        }

        /// <summary>
        /// 获取返回时的签名验证结果
        /// </summary>
        /// <param name="inputPara">通知返回参数数组</param>
        /// <param name="sign">对比的签名结果</param>
        /// <returns>签名验证结果</returns>
        private bool GetSignVeryfy(SortedDictionary<string, string> inputPara, string sign)
        {
            Dictionary<string, string> sPara = new Dictionary<string, string>();

            //过滤空值、sign与sign_type参数
            sPara = Core.FilterPara(inputPara);
            
            //获取待签名字符串
            string preSignStr = Core.CreateLinkString(sPara);

            //获得签名验证结果
            bool isSgin = false;
            if (sign != null && sign != "")
            {
                switch (_sign_type)
                {
                    case "MD5":
                        isSgin = AlipayMD5.Verify(preSignStr, sign, _key, _input_charset);
                        break;
                    default:
                        break;
                }
            }

            return isSgin;
        }

        /// <summary>
        /// 获取是否是支付宝服务器发来的请求的验证结果
        /// </summary>
        /// <param name="notify_id">通知验证ID</param>
        /// <returns>验证结果</returns>
        private string GetResponseTxt(string notify_id)
        {
            string veryfy_url = Https_veryfy_url + "partner=" + _partner + "¬ify_id=" + notify_id;

            //获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求
            string responseTxt = Get_Http(veryfy_url, 1200000);

            return responseTxt;
        }

        /// <summary>
        /// 获取远程服务器ATN结果
        /// </summary>
        /// <param name="strUrl">指定URL路径地址</param>
        /// <param name="timeout">超时时间设置</param>
        /// <returns>服务器ATN结果</returns>
        /// false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟  
        private string Get_Http(string strUrl, int timeout)
        {
            string strResult;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Timeout = timeout;
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.Default);
                StringBuilder strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }

                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {
                strResult = "错误:" + exp.Message;
            }

            return strResult;
        }
    }
}


 




 
 

                
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
学成在线采用支付API作为其在线支付的方式。支付API支付提供的一套接口,用于实现在线支付功能。通过支付API,学成在线可以与支付进行数据交互,实现用户在学成在线平台上购买课程、充值等操作时的支付功能。具体的支付流程包括用户选择支付作为支付方式、跳转到支付支付页面、用户输入支付密码并确认支付支付返回支付结果等步骤。学成在线借鉴了支付支付流程的设计思想,并根据自身需求进行了定制化开发,以提供更好的支付体验和安全性。 #### 引用[.reference_title] - *1* *2* [学成在线笔记一:项目概述与CMS接口开发](https://blog.csdn.net/qq1031893936/article/details/106772176)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [搞定支付接口(一) 支付即时到账支付接口详细流程和代码](https://blog.csdn.net/tom9238/article/details/70213528)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值