今天小编带大家来分析一下微信小程序支付功能的实现全过程。
整体流程:
支付统一下单接口说明:
接口链接:https://api.mch.weixin.qq.com/pay/unifiedorder
具体参数可以参考微信开发文档https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1
这里我附一下代码:
//统一下单接口编写
[HttpGet]
public string pay(string openid)
{
string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//创建键值对
var dic = new Dictionary<string, string>
{
{"appid", "**************"}, //微信appid
{"body","it's very good"}, //body 商品简单描述
{"mch_id", "************"}, //商户号
{"nonce_str", "5K8264ILTKCH16CQ2502SI8ZNMTM67VS"}, //随机字符串(20)
{"notify_url","http://www.weixin.qq.com/wxpay/pay.php"}, //异步通知的地址
{"openid",openid}, //openid
{"out_trade_no","20150806125346"}, //商户自己的订单号码
{"spbill_create_ip","192.168.138.1"}, //IP地址
{"total_fee","1"}, //支付多少钱
{"trade_type","JSAPI" }, //交易类型 JSAPI
{"sign","******************" } //签名
};
var sb = new StringBuilder();
sb.Append("" );
foreach (var d in dic)
{
sb.Append("<" + d.Key + ">" + d.Value + "" + d.Key + ">");
}
sb.Append("");
string new_sb = sb + "";
byte[] bs = Encoding.ASCII.GetBytes(new_sb);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bs.Length;
request.GetRequestStream().Write(bs, 0, bs.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
这些参数里面最复杂的就是sign——签名,它的生成有自己一套独立的算法。
具体内容见微信开发文档https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3
wx.requestPayment接口说明:
wx.requestPayment({
'timeStamp': '',
'nonceStr': '',
'package': '',
'signType': 'MD5',
'paySign': '',
'success':function(res){
dosomething();
},
'fail':function(res){
console.log(res);
}
})
参数在服务器端返回的数据里面都包括了,只要调用一下即可。