首页 > 代码库 > C# 微支付 JSAPI支付方式 V3.3.6版本
C# 微支付 JSAPI支付方式 V3.3.6版本
<script type="text/javascript">
//结算 (订单号)
function PayClearing(num) {
$.ajax({
type: "POST",
url: "/***/handler/***.ashx",
data: "otype=Account&ids=" + num ,
async: false,
success: function (msg) {
if (msg == "-99") {
alert("请先关注该公众号,再进行下单操作!");
} else if (msg == "1") {
alert("出现未知的错误,请联系管理员!");
} else if (msg == "2") {
alert("请选择您要支付的订单!");
} else { //返回预支付ID
var argument = msg.split(",");
//前台H5调用
WeixinJSBridge.invoke(‘getBrandWCPayRequest‘, {
"appId": argument[0], //公众号AppID
"timeStamp": argument[1], //时间戳
"nonceStr": argument[2], //随机串
"package": argument[3], //扩展包
"signType": "MD5", //微信签名方式:MD5
"paySign": argument[4] //微信签名
}, function (res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
alert("支付完成");
}
});
}
}
});
}
</script>
#region 使用微支付统一接口,返回预支付ID
/// <summary>
/// 使用微支付统一接口,返回预支付ID
/// </summary>
/// <param name="context"></param>
/// <param name="returnMsg"></param>
/// <returns></returns>
private bool PayAccount(HttpContext context,ref string returnMsg)
{
int UID = 0;
int Address = 0;
string OIDs = ""; //订单号
if (context.Request["ids"].TrimStart(‘,‘).TrimEnd(‘,‘).Length > 0)
{
OIDs = context.Request["ids"].TrimStart(‘,‘).TrimEnd(‘,‘);
order = *BLL.GetModel(Convert.ToInt32(OIDs)); //获取订单实体
}
else
{
returnMsg = "选择您要支付的订单";//选择您要支付的订单
return false;
}
//判断是否使用优惠券
int privilege = 0; //优惠的money
if(order.**ID.ToString()!="0" && order.**ID.ToString()!="") //有优惠券的ID 则使用
{
privilege = Convert.ToInt32((order.*Price)*100); //优惠的money
}
int Money = 0;
int isWZTest =Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["isWZFTest"]);
if (isWZTest == 1) //测试
{
Money = 1;
}
else //正常计费
{
Money =Convert.ToInt32 (Convert.ToInt32(((order.**Price + order.**ight) * 100))-privilege);//支付金额为订单总金额加运费减去优惠的money
}
string Nonce = CreateRandomCode(15).ToLower(); //生成15个随机字符
string sign1 = "appid=" +PayHandle.AppID.ToString()+ //微信公众号的AppID
"&body=" + ProtectName + //商品描述
"&mch_id=" +PayHandle.MechID.ToString()+ //商户号
"&nonce_str=" + Nonce + //随机字符串
"¬ify_url=http://***.com/***/Notify/PayNotify.aspx" + //微支付支付成功的通知路径
"&openid=" + **.OpenID + //微信用户的OpenID
"&out_trade_no=" + ***.Code + //商户的订单标识
"&spbill_create_ip=***.**.**.**" + //服务器IP
//订单失效时间为创建订单时间后15天
"&time_expire=" + **.CreateTime.AddDays(15).ToString("yyyyMMddHHmmss") +
"&time_start=" + **.CreateTime.ToString("yyyyMMddHHmmss") + //订单创建时间
//支付的价钱 以分为单位
"&total_fee=" + Money +
"&trade_type=JSAPI"; //交易类型
string sign2 = sign1 + "&key="+PayHandle.PayKey.ToString(); //在微支付里面设置的key
string sign = T9.Util.EncryptUtil.md5(sign2, 32).ToUpper(); //签名(采用MD5加密)
string URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //统一支付接口
string RequstContext = "<xml>" +
"<appid><![CDATA[" + PayHandle.AppID.ToString() + "]]></appid>" +
"<mch_id>"+ PayHandle.MechID.ToString() +"</mch_id>" +
"<nonce_str><![CDATA[" + Nonce + "]]></nonce_str>" +
"<sign><![CDATA[" + sign + "]]></sign>" +
"<body><![CDATA[" + ProtectName + "]]></body>" +
"<out_trade_no><![CDATA[" + **.Code + "]]></out_trade_no>" +//商户的订单标识
"<total_fee>" + Money + "</total_fee>" +//支付金额(以分为单位)
"<spbill_create_ip>***.**.**.**</spbill_create_ip>" +//服务器的IP
"<time_start>" + **.CreateTime.ToString("yyyyMMddHHmmss") + "</time_start>" + //订单创建时间
"<time_expire>" + **.CreateTime.AddDays(15).ToString("yyyyMMddHHmmss") + "</time_expire>" +//订单失效时间
"<notify_url>http://***.com/***/Notify/PayNotify.aspx</notify_url>" + //微支付支付成功的通知路径
"<trade_type><![CDATA[JSAPI]]></trade_type>" +
"<openid><![CDATA[" + **.OpenID + "]]></openid>" + //微信用户的OpenID
"</xml>";
string PayInfo = SendInfo(URL, RequstContext); //微支付返回的数据
XmlDocument doc = new XmlDocument();
doc.LoadXml(PayInfo);
XmlElement rootElement = doc.DocumentElement;
string Code = rootElement.SelectSingleNode("return_code").InnerText; //协议级判断
if (Code == "SUCCESS")
{
string ResultCode=rootElement.SelectSingleNode("result_code").InnerText;//业务及判断
if (ResultCode == "SUCCESS")
{
string prepay = rootElement.SelectSingleNode("prepay_id").InnerText; //预支付ID
if (prepay.ToString() != "")
{
int timeStamp = ConvertDateTimeInt(DateTime.Now); //时间戳
string appId = PayHandle.AppID.ToString(); //公众号的APPID
string nonceStr = CreateRandomCode(15).ToLower(); //15个随机字符串
string package="prepay_id="+prepay;
string signTemp = "appId=" + appId +
"&nonceStr=" + nonceStr +
"&package=" + package +
"&signType=MD5" +
"&timeStamp=" + timeStamp +
"&key=" + PayHandle.PayKey.ToString();
string strsign = T9.Util.EncryptUtil.md5(signTemp, 32).ToUpper(); //签名
returnMsg = appId + "," + timeStamp + "," + nonceStr + "," + package + "," + strsign; //返回H5支付需要的参数,方便调用
return true;
}
else
{
returnMsg = "出现未知的错误,请联系管理员";//出现未知的错误,请联系管理员
return false;
}
}
else
{
returnMsg = "出现未知的错误,请联系管理员";//出现未知的错误,请联系管理员
return false;
}
}
else
{
returnMsg = "出现未知的错误,请联系管理员";//出现未知的错误,请联系管理员
return false;
}
}
#endregion
#region 生成随机字符串
/// <summary>
/// 生成随机字符串
/// </summary>
/// <param name="codeCount"></param>
/// <param name="allChar"></param>
/// <returns></returns>
public static string CreateRandomCode(int codeCount)
{
//验证码中的出现的字符,避免了一些容易混淆的字符。
string allChar = "3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,T,U,W,X,Y";
string[] allCharArray = allChar.Split(‘,‘);
string randomCode = "";
int temp = -1;
bool breCreate = (codeCount < 6 && allCharArray.Length > 15);
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(allCharArray.Length);
if (temp == t && breCreate)
{
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
#endregion
#region 向微信服务器发送信息
/// <summary>
/// 向微信服务器发送信息
/// </summary>
/// <param name="posturl"></param>
/// <param name="postData"></param>
/// <returns></returns>
public string SendInfo(string posturl, string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
byte[] data = http://www.mamicode.com/encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(posturl) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
T9.Util.LogUtil.WriteLog(ex.Message + "\r\n" + ex.StackTrace, "WebLog");
return string.Empty;
}
}
#endregion
#region datetime转换为unixtime
/// <summary>
/// datetime转换为unixtime
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
#endregion
C# 微支付 JSAPI支付方式 V3.3.6版本