c# 微信小程序添加卡券签名_微信小程序之微信支付C#后台(统一下单)

本文介绍了如何使用C#后台为微信小程序实现支付功能,包括统一下单接口调用、签名生成步骤,以及支付结果通知API的处理。详细讲解了涉及的参数设置和签名算法,并提供了相关代码示例。
摘要由CSDN通过智能技术生成

一、微信小程序支付

1、微信小程序端请求支付接口

商户在小程序中先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易后调起支付。具体可以查看。

接口传入参数示例:

wx2421b1c4370ec43b

支付测试

10000100

1add1a30ac87aa2db72f57a2375d8fec

http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php

oupf8umuajo_m2pxb1q9znjwes6o

1415659990

14.23.150.211

1

jsapi

0cb01533b8c1ef103065174f50bca001

接口返回示例:

二、接口调用(c#)

1、支付接口方法

//获取请求数据

dictionary strparam = new dictionary();

//小程序id

strparam.add("appid", payinfo.appid);

//附加数据

strparam.add("attach", payinfo.attach);

//商品描述

strparam.add("body", payinfo.body);

//商户号

strparam.add("mch_id", payinfo.mchid);

//随机字符串

strparam.add("nonce_str", payinfo.noncestr);

//通知地址 (异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。)

strparam.add("notify_url", payinfo.notifyurl);

//用户标识

strparam.add("openid", openid);

//商户订单号

strparam.add("out_trade_no", ordernum);

//终端ip

strparam.add("spbill_create_ip", payinfo.addrip);

//标价金额

strparam.add("total_fee", convert.toint32(ordertotal * 100).tostring());

//交易类型

strparam.add("trade_type", payinfo.tradetype);

strparam.add("sign", payhelper.getsigninfo(strparam, payinfo.key));

//获取预支付id

string preinfo = utility.posthttpresponse(payinfo.orderurl, payhelper.createxmlparam(strparam));

string strcode = payhelper.getxmlvalue(preinfo, "return_code");

string strmsg = payhelper.getxmlvalue(preinfo, "return_msg");

if (strcode == "success")

{

//再次签名

string nonecstr = payinfo.noncestr;

string timestamp = payinfo.timestamp;

string package = "prepay_id=" + payhelper.getxmlvalue(preinfo, "prepay_id");

dictionary singinfo = new dictionary();

singinfo.add("appid", payinfo.appid);

singinfo.add("noncestr", nonecstr);

singinfo.add("package", package);

singinfo.add("signtype", payinfo.signtype);

singinfo.add("timestamp", timestamp);

//返回参数

info.msg = strmsg;

info.code = strcode;

info.id = orderid;

info.appid = payinfo.appid;

info.orderguid = ordernum;

info.package = package;

info.timestamp = timestamp;

info.noncestr = nonecstr;

info.signtype = payinfo.signtype;

info.paysign = payhelper.getsigninfo(singinfo, payinfo.key);

listmsg.add(info);

result = u.successmsg(listmsg, "", "");

}

else

{

info.code = strcode;

info.msg = strmsg;

listmsg.add(info);

result = u.failmsg(listmsg);

}

2、支付结果通知api

///

/// 支付结果通知api

///

///

[httppost]

public string ordernotify()

{

string strresult = string.empty;

try

{

//1.获取微信通知的参数

string strxml = utility.getpoststr();

//判断是否请求成功

if (payhelper.getxmlvalue(strxml, "return_code") == "success")

{

//判断是否支付成功

if (payhelper.getxmlvalue(strxml, "result_code") == "success")

{

//获得签名

string getsign = payhelper.getxmlvalue(strxml, "sign");

//进行签名

string sign = payhelper.getsigninfo(payhelper.getfromxml(strxml), payinfo.key);

if (sign == getsign)

{

//校验订单信息

string wxordernum = payhelper.getxmlvalue(strxml, "transaction_id"); //微信订单号

string ordernum = payhelper.getxmlvalue(strxml, "out_trade_no"); //商户订单号

string ordertotal = payhelper.getxmlvalue(strxml, "total_fee");

string openid = payhelper.getxmlvalue(strxml, "openid");

//校验订单是否存在

if (true)

{

//2.更新订单的相关状态

//3.返回一个xml格式的结果给微信服务器

if (obj > 0)

{

strresult = payhelper.getreturnxml("success", "ok");

}

else

{

strresult = payhelper.getreturnxml("fail", "订单状态更新失败");

}

}

else

{

strresult = payhelper.getreturnxml("fail", "支付结果中微信订单号数据库不存在!");

}

}

else

{

strresult = payhelper.getreturnxml("fail", "签名不一致!");

}

}

else

{

strresult = payhelper.getreturnxml("fail", "支付通知失败!");

}

}

else

{

strresult = payhelper.getreturnxml("fail", "支付通知失败!");

}

#endregion

}

catch (exception ex)

{

}

return strresult;

}

3、utility类

///

/// 获得post过来的数据

///

///

public static string getpoststr()

{

int32 intlen = convert.toint32(httpcontext.current.request.inputstream.length);

byte[] b = new byte[intlen];

httpcontext.current.request.inputstream.read(b, 0, intlen);

return encoding.utf8.getstring(b);

}

///

/// 模拟post提交

///

/// 请求地址

/// xml参数

/// 返回结果

public static string posthttpresponse(string url, string xmlparam)

{

httpwebrequest myhttpwebrequest = (httpwebrequest)httpwebrequest.create(url);

myhttpwebrequest.method = "post";

myhttpwebrequest.contenttype = "application/x-www-form-urlencoded;charset=utf-8";

// encode the data

byte[] encodedbytes = encoding.utf8.getbytes(xmlparam);

myhttpwebrequest.contentlength = encodedbytes.length;

// write encoded data into request stream

stream requeststream = myhttpwebrequest.getrequeststream();

requeststream.write(encodedbytes, 0, encodedbytes.length);

requeststream.close();

httpwebresponse result;

try

{

result = (httpwebresponse)myhttpwebrequest.getresponse();

}

catch

{

return string.empty;

}

if (result.statuscode == httpstatuscode.ok)

{

using (stream mystream = result.getresponsestream())

{

using (streamreader reader = new streamreader(mystream))

{

return reader.readtoend();

}

}

}

return null;

}

4、payhelper类

#region 生成签名

///

/// 获取签名数据

///

///

///

///

public static string getsigninfo(dictionary strparam, string key)

{

int i = 0;

string sign = string.empty;

stringbuilder sb = new stringbuilder();

try

{

foreach (keyvaluepair temp in strparam)

{

if (temp.value == "" || temp.value == null || temp.key.tolower() == "sign")

{

continue;

}

i++;

sb.append(temp.key.trim() + "=" + temp.value.trim() + "&");

}

sb.append("key=" + key.trim() + "");

sign = md5core.gethashstring(sb.tostring(), encoding.utf8).toupper();

}

catch (exception ex)

{

utility.addlog("payhelper", "getsigninfo", ex.message, ex);

}

return sign;

}

#endregion

#region xml 处理

///

/// 获取xml值

///

/// xml字符串

/// 字段值

///

public static string getxmlvalue(string strxml, string strdata)

{

string xmlvalue = string.empty;

xmldocument xmldocument = new xmldocument();

xmldocument.loadxml(strxml);

var selectsinglenode = xmldocument.documentelement.selectsinglenode(strdata);

if (selectsinglenode != null)

{

xmlvalue = selectsinglenode.innertext;

}

return xmlvalue;

}

///

/// 集合转换xml数据 (拼接成xml请求数据)

///

/// 参数

///

public static string createxmlparam(dictionary strparam)

{

stringbuilder sb = new stringbuilder();

try

{

sb.append("");

foreach (keyvaluepair k in strparam)

{

if (k.key == "attach" || k.key == "body" || k.key == "sign")

{

sb.append("" + k.key + ">");

}

else

{

sb.append("" + k.value + "" + k.key + ">");

}

}

sb.append("");

}

catch (exception ex)

{

utility.addlog("payhelper", "createxmlparam", ex.message, ex);

}

return sb.tostring();

}

///

/// xml数据转换集合(xml数据拼接成字符串)

///

///

///

public static dictionary getfromxml(string xmlstring)

{

dictionary sparams = new dictionary();

try

{

xmldocument doc = new xmldocument();

doc.loadxml(xmlstring);

xmlelement root = doc.documentelement;

int len = root.childnodes.count;

for (int i = 0; i < len; i++)

{

string name = root.childnodes[i].name;

if (!sparams.containskey(name))

{

sparams.add(name.trim(), root.childnodes[i].innertext.trim());

}

}

}

catch (exception ex)

{

utility.addlog("payhelper", "getfromxml", ex.message, ex);

}

return sparams;

}

///

/// 返回通知 xml

///

///

///

///

public static string getreturnxml(string returncode, string returnmsg)

{

stringbuilder sb = new stringbuilder();

sb.append("");

sb.append("");

sb.append("");

sb.append("");

return sb.tostring();

}

#endregion

5、payinfo类

public class payinfo

{

///

/// 小程序登录api

///

public static string loginurl = configurationmanager.appsettings["loginurl"].tostring();

///

/// 统一下单api

///

public static string orderurl = configurationmanager.appsettings["orderurl"].tostring();

///

/// 支付结果通知api

///

public static string notifyurl = configurationmanager.appsettings["notifyurl"].tostring();

///

/// 查询订单api

///

public static string queryurl = configurationmanager.appsettings["queryurl"].tostring();

///

/// 申请退款api

///

public static string refundurl = configurationmanager.appsettings["refundurl"].tostring();

///

/// 退款通知api

///

public static string refundnotifyurl = configurationmanager.appsettings["refundnotifyurl"].tostring();

///

/// 退款通知api

///

public static string refundqueryurl = configurationmanager.appsettings["refundqueryurl"].tostring();

///

/// 小程序唯一标识

///

public static string appid = configurationmanager.appsettings["appid"].tostring();

///

/// 小程序的 app secret

///

public static string secret = configurationmanager.appsettings["secret"].tostring();

///

/// 小程序的授权类型

///

public static string granttype = configurationmanager.appsettings["grant_type"].tostring();

///

/// 商户号(微信支付分配的商户号)

///

public static string mchid = configurationmanager.appsettings["mch_id"].tostring();

///

///商户平台设置的密钥key

///

public static string key = configurationmanager.appsettings["key"].tostring();

///

/// 随机字符串不长于 32 位

///

public static string noncestr = payhelper.getnoncestr();

///

/// 时间戳 从1970年1月1日00:00:00至今的秒数,即当前的时间

///

public static string timestamp = payhelper.gettimestamp();

///

/// 终端ip app和网页支付提交用户端ip,

///

public static string addrip = payhelper.getip;

///

/// 交易类型 小程序取值如下:jsapi

///

public static string tradetype = "jsapi";

///

/// 签名类型 默认为md5,支持hmac-sha256和md5。

///

public static string signtype = "md5";

///

/// 商品描述 商品简单描述,该字段请按照规范传递

///

public static string body = "奇小爱的异想世界-支付";

///

/// 附加数据 在查询api和支付通知中原样返回

///

public static string attach = "微信支付信息";

///

/// 签名,参与签名参数:appid,mch_id,transaction_id,out_trade_no,nonce_str,key

///

public string sign = "";

///

/// 微信订单号,优先使用

///

public static string transactionid = "";

///

/// 商户系统内部订单号

///

public static string out_trade_no = "";

///

/// 商户退款单号

///

public static string out_refund_no = "";

///

/// 退款金额

///

public static decimal refundfee;

///

/// 订单金额

///

public static decimal totalfee;

}

三、微信小程序调用

1、小程序调用方法,发起支付,具体如下:

微信小程序支付方。

2、示例代码:

wx.requestpayment({

'timestamp': '',

'noncestr': '',

'package': '',

'signtype': 'md5',

'paysign': '',

'success':function(res){

},

'fail':function(res){

}

})

3、测试完成支付

优秀是一种习惯,欢迎大家关注学习

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值