您好,登录后才能下订单哦!
后台
public ActionResult WxAddVoucher_Center(double money)
{
int money= int.Parse((money * 100).ToString());
String ip = Request.UserHostAddress;
//随机商品ID
String id = "";
Random rd = new Random();
for (int i = 1; i < 16; i++)
{
id += (rd.Next(0, 9)).ToString();
}
PayMent pm=new PayMent();
String WeixinAPI = pm.JSAPIPayMent("商品描述", openid, ip, money, id);
return Content(WeixinAPI);
}
配置微信支付的必须参数
public class Wxconfig{
public const string appid = "";//公众号ID
public const string secret = "";//微信公众号的secret
public const string url = "";//回调url
public const string mch_id = "";//商户号
public const string paysignkey = "";//证书密匙
}
// 定义返回JSON数据类型的微信支付方法
public class PayMent
/// <summary>
/// 微信支付
/// </summary>
/// <param name="boby">商品描述</param>
/// <param name="mch_id">商户号</param>
/// <param name="openid">用户openid</param>
/// <param name="spbill_create_ip">终端IP</param>
/// <param name="total_fee">金额</param>
/// <param name="out_trade_no">商户订单号</param>
/// <returns></returns>
public String JSAPIPayMent( string boby, string openid, string spbill_create_ip, int total_fee, string out_trade_no)
{
UnifiedOrder order = new UnifiedOrder();
order.appid = WXconfig.appid;
order.attach = "vinson";
order.body = boby;
order.device_info = "";
order.mch_id = WXconfig.mch_id;
order.nonce_str = TenpayUtil.getNoncestr();
order.notify_url = WXconfig.url;
order.openid = openid;
order.out_trade_no = out_trade_no;
order.trade_type = "JSAPI";
order.spbill_create_ip = spbill_create_ip;
order.total_fee = total_fee;
TenpayUtil tenpay = new TenpayUtil();
string paySignKey = WXconfig.paysignkey;
string prepay_id = tenpay.getPrepay_id(order, paySignKey);
string timeStamp = TenpayUtil.getTimestamp();
string nonceStr = TenpayUtil.getNoncestr();
SortedDictionary<string, object> sParams = new SortedDictionary<string, object>();
sParams.Add("appId", WXconfig.appid);
sParams.Add("timeStamp", timeStamp);
sParams.Add("nonceStr", nonceStr);
sParams.Add("package", "prepay_id=" + prepay_id);
sParams.Add("signType", "MD5");
string paySign = tenpay.getsign(sParams, paySignKey);
string package = "prepay_id=" + prepay_id;
return MD5Util.toJson(WXconfig.appid, timeStamp, nonceStr, package, "MD5", paySign);
}
}
//-------TenpayUtil类
public class TenpayUtil
{
/// <summary>
/// 统一支付接口
/// </summary>
const string UnifiedPayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
/// <summary>
/// 随机串
/// </summary>
public static string getNoncestr()
{
Random random = new Random();
return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK").ToLower().Replace("s", "S");
}
/// <summary>
/// 时间截,自1970年以来的秒数
/// </summary>
public static string getTimestamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/// <summary>
/// 获取微信签名
/// </summary>
/// <param name="sParams"></param>
/// <returns></returns>
public string getsign(SortedDictionary<string, object> sParams, string key)
{
int i = 0;
string sign = string.Empty;
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, object> temp in sParams)
{
if (temp.Value.ToString() == "" || temp.Value == null || temp.Key.ToLower() == "sign")
{
continue;
}
i++;
sb.Append(temp.Key.Trim() + "=" + temp.Value.ToString() + "&");
}
sb.Append("key=" + key.Trim() + "");
string signkey = sb.ToString();
sign = MD5Util.GetMD5(signkey, "utf-8");
//utf-8
return sign;
}
/// <summary>
/// post数据到指定接口并返回数据
/// </summary>
public string PostXmlToUrl(string url, string postData)
{
string returnmsg = "";
//Byte[] temp = Encoding.UTF8.GetBytes(postData);
//string dataGBK = Encoding.GetEncoding("GBK").GetString(temp);
using (System.Net.WebClient wc = new System.Net.WebClient())
{
returnmsg = wc.UploadString(url, "POST", postData);
}
return returnmsg;
}
/// <summary>
/// 获取prepay_id
/// </summary>
public string getPrepay_id(UnifiedOrder order, string key)
{
string prepay_id = "";
string post_data = getUnifiedOrderXml(order, key);
string request_data = PostXmlToUrl(UnifiedPayUrl, post_data);
//Log.WriteLog1(request_data);
SortedDictionary<string, object> requestXML = GetInfoFromXml(request_data);
foreach (KeyValuePair<string, object> k in requestXML)
{
if (k.Key == "prepay_id")
{
prepay_id = k.Value.ToString();
break;
}
}
return prepay_id;
}
/// <summary>
/// 把XML数据转换为SortedDictionary<string, string>集合
/// </summary>
/// <param name="strxml"></param>
/// <returns></returns>
protected SortedDictionary<string, object> GetInfoFromXml(string xmlstring)
{
SortedDictionary<string, object> sParams = new SortedDictionary<string, object>();
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 { }
return sParams;
}
/// <summary>
/// 微信统一下单接口xml参数整理
/// </summary>
/// <param name="order">微信支付参数实例</param>
/// <param name="key">密钥</param>
/// <returns></returns>
protected string getUnifiedOrderXml(UnifiedOrder order, string key)
{
string return_string = string.Empty;
SortedDictionary<string, object> sParams = new SortedDictionary<string, object>();
sParams.Add("appid", order.appid);
sParams.Add("attach", order.attach);
sParams.Add("body", order.body);
sParams.Add("device_info", order.device_info);
sParams.Add("mch_id", order.mch_id);
sParams.Add("nonce_str", order.nonce_str);
sParams.Add("notify_url", order.notify_url);
sParams.Add("openid", order.openid);
sParams.Add("out_trade_no", order.out_trade_no);
sParams.Add("spbill_create_ip", order.spbill_create_ip);
sParams.Add("total_fee", order.total_fee);
sParams.Add("trade_type", order.trade_type);
order.sign = getsign(sParams, key);
sParams.Add("sign", order.sign);
//拼接成XML请求数据
StringBuilder sbPay = new StringBuilder();
foreach (KeyValuePair<string, object> k in sParams)
{
if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
{
sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
}
else
{
sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
}
}
return_string = string.Format("<xml>{0}</xml>", sbPay.ToString());
byte[] byteArray = Encoding.UTF8.GetBytes(return_string);
return_string = Encoding.GetEncoding("GBK").GetString(byteArray);
Byte[] temp = Encoding.UTF8.GetBytes(return_string);
string dataGBK = Encoding.GetEncoding("utf-8").GetString(temp);
return return_string;
// GBK
}
}
//---微信统一接口请求实体对象
/// <summary>
/// 微信统一接口请求实体对象
/// </summary>
[Serializable]
public class UnifiedOrder
{
/// <summary>
/// 公众号ID(微信分配的公众账号 ID)
/// </summary>
public string appid = "";
/// <summary>
/// 商户号(微信支付分配的商户号)
/// </summary>
public string mch_id = "";
/// <summary>
/// 微信支付分配的终端设备号
/// </summary>
public string device_info = "";
/// <summary>
/// 随机字符串,不长于 32 位
/// </summary>
public string nonce_str = "";
/// <summary>
/// 签名
/// </summary>
public string sign = "";
/// <summary>
/// 商品描述
/// </summary>
public string body = "";
/// <summary>
/// 附加数据,原样返回
/// </summary>
public string attach = "";
/// <summary>
/// 商户系统内部的订单号,32个字符内、可包含字母,确保在商户系统唯一,详细说明
/// </summary>
public string out_trade_no = "";
/// <summary>
/// 订单总金额,单位为分,不能带小数点
/// </summary>
public int total_fee = 0;
/// <summary>
/// 终端IP
/// </summary>
public string spbill_create_ip = "";
/// <summary>
/// 订 单 生 成 时 间 , 格 式 为yyyyMMddHHmmss,如 2009 年12 月 25 日 9 点 10 分 10 秒表示为 20091225091010。时区为 GMT+8 beijing。该时间取自商户服务器
/// </summary>
public string time_start = "";
/// <summary>
/// 交易结束时间
/// </summary>
public string time_expire = "";
/// <summary>
/// 商品标记 商品标记,该字段不能随便填,不使用请填空,使用说明详见第 5 节
/// </summary>
public string goods_tag = "";
/// <summary>
/// 接收微信支付成功通知
/// </summary>
public string notify_url = "";
/// <summary>
/// JSAPI、NATIVE、APP
/// </summary>
public string trade_type = "";
/// <summary>
/// 用户标识 trade_type 为 JSAPI时,此参数必传
/// </summary>
public string openid = "";
/// <summary>
/// 只在 trade_type 为 NATIVE时需要填写。
/// </summary>
public string product_id = "";
}
// 转JSon对象
/// <summary>
/// json
/// </summary>
/// <returns></returns>
public static String toJson(string appId, string timeStamp, string nonceStr, string packageA, string signType, string paySign)
{
String json = "{";
json += "\"appId\":" + "\"" + appId + "\",";
json += "\"timeStamp\":" + "\"" + timeStamp + "\",";
json += "\"nonceStr\":" + "\"" + nonceStr + "\",";
json += "\"package\":" + "\"" + packageA + "\",";
json += "\"signType\":" + "\"" + signType + "\",";
json += "\"paySign\":" + "\"" + paySign + "\"";
json += "}";
return json;
}
前端代码
<input id="btn" type="button" value="充值"/>
<script>
$("#btn").click(function () {
$.get(url,data, function (t) {//其中url是后台地址,data是金额
var r = $.parseJSON(t);
callpay(r);
}
})
//支付功能
function jsApiCall(r) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest', r,
function (res) {
//alert(res.err_code + res.err_desc);
//alert(res.err_msg);
if (res.err_msg == "get_brand_wcpay_request:ok") {
alert(”支付成功”);
} else {
alert("交易取消");
}
}
);
}
function callpay(r) {
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
} else {
jsApiCall(r);
}
}
</script>
项目地址:https://gitee.com/qq-w/wechat.git
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。