Re0:用.Net写一个微信公众号
程序员文章站
2022-07-11 08:21:11
直奔主题,写一个公众号。包含基本微信前端效果,常用的增删改查功能、支付回调功能、推送消息功能。 暂时想到这么多。 首先感谢官方提供的好东西(请忽略版本号(╯‵□′)╯︵┻━┻) 有点用的签名算法 有点用的Token 有点用的微信js 生成微信Alert 生成微信支付的签名 生成微信支付用的js 微信 ......
直奔主题,写一个公众号。包含基本微信前端效果,常用的增删改查功能、支付回调功能、推送消息功能。
暂时想到这么多。
首先感谢官方提供的好东西(请忽略版本号(╯‵□′)╯︵┻━┻)
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
有点用的签名算法
/// <summary> /// 签名算法 /// </summary> /// <param name="jsapi_ticket">jsapi_ticket</param> /// <param name="noncestr">随机字符串(必须与wx.config中的noncestr相同)</param> /// <param name="timestamp">时间戳(必须与wx.config中的timestamp相同)</param> /// <param name="url">当前网页的url,不包含#及其后面部分(必须是调用js接口页面的完整url)</param> /// <returns></returns> public static string getsignature(string jsapi_ticket, string noncestr, long timestamp, string url, out string string1)// 生成微信接口的签名 { stringbuilder string1builder = new stringbuilder(); string1builder.append("jsapi_ticket=").append(jsapi_ticket).append("&") .append("noncestr=").append(noncestr).append("&") .append("timestamp=").append(timestamp).append("&") .append("url=").append(url.indexof("#") >= 0 ? url.substring(0, url.indexof("#")) : url); string1 = string1builder.tostring(); return formsauthentication.hashpasswordforstoringinconfigfile(string1, "sha1"); }
有点用的token
/// <summary> /// 获取access_token /// </summary> /// <returns></returns> public static string getaccesstoken()// 获取access_token { string appid = system.configuration.configurationmanager.appsettings["appid"]; string appsecret = system.configuration.configurationmanager.appsettings["appsecret"]; conndb db = new conndb(); datarow dr = db.returndatatable("select token,time from balabulabula ").rows[0]; string access_token = dr["token"].tostring(); string yxq = dr["time"].tostring(); if (yxq == "") yxq = "2016-01-01"; if (datetime.now >= datetime.parse(yxq)) { access_token = parsefromjson<access_token>(getpage("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret, "")).access_token; db.editdatabase("update bulabulabula set token='" + access_token + "',time=convert(varchar(20),dateadd(ss,6000,getdate()),120) where mc='access_token'"); } return access_token; }
有点用的微信js
/// <summary> /// 生成微信配置js /// </summary> /// <returns></returns> public static string wxconfig()// 生成微信配置js { conndb db = new conndb(); string url = httpcontext.current.request.url.absoluteuri; if (url.indexof('#') > 0) url = url.substring(0, url.indexof('#')); string appid = system.configuration.configurationmanager.appsettings["appid"]; datarow dr = db.returndatatable("select token,time from bulabulabula'").rows[0]; string jsapi_ticket = dr["token"].tostring(); string yxq = dr["time"].tostring(); if (yxq == "") yxq = "2016-01-01"; if (datetime.now >= datetime.parse(yxq)) { string access_token = getaccesstoken(); jsapi_ticket = parsefromjson<jsapi_ticket>(getpage("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi", "")).ticket; db.editdatabase("update bualbulabula set token='" + jsapi_ticket + "',time=convert(varchar(20),dateadd(ss,6000,getdate()),120) "); } string noncestr = creatennonce_str(); long timestamp = createntimestamp(); string str1; string signature = getsignature(jsapi_ticket, noncestr, timestamp, url, out str1); return @" <script type='text/javascript'> wx.error(function (res) { alert(res.errmsg); }); wx.config({ debug: false, appid: '" + appid + @"', timestamp: " + timestamp.tostring() + @", noncestr: '" + noncestr + @"', signature: '" + signature + @"', jsapilist: ['scanqrcode', 'chooseimage', 'uploadimage', 'getlocation', 'openlocation'] }); function wxalert(txt) { $('#dlg_alert').show(); $('#wxdlg_alert_text').text(txt); } </script> <link href='css/weui.min.css' rel='stylesheet'/> <div class='weui_dialog_alert' id='dlg_alert' style='display: none;'> <div class='weui_mask'></div> <div class='weui_dialog'> <div class='weui_dialog_hd'><strong class='weui_dialog_title'>提示</strong></div> <div class='weui_dialog_bd' id='wxdlg_alert_text'>弹窗内容,告知当前页面信息等</div> <div class='weui_dialog_ft'> <a href=""javascript:$('#dlg_alert').hide();"" class='weui_btn_dialog primary'>确定</a> </div> </div> </div>"; }
生成微信alert
/// <summary> /// 生成微信alert /// </summary> /// <returns></returns> public static string wxalert()// 生成微信alert { return @" <script type='text/javascript'> function wxalert(txt) { $('#dlg_alert').show(); $('#wxdlg_alert_text').text(txt); } </script> <link href='css/weui.min.css' rel='stylesheet'/> <div class='weui_dialog_alert' id='dlg_alert' style='display: none;'> <div class='weui_mask'></div> <div class='weui_dialog'> <div class='weui_dialog_hd'><strong class='weui_dialog_title'>提示</strong></div> <div class='weui_dialog_bd' id='wxdlg_alert_text'>弹窗内容,告知当前页面信息等</div> <div class='weui_dialog_ft'> <a href=""javascript:$('#dlg_alert').hide();"" class='weui_btn_dialog primary'>确定</a> </div> </div> </div>"; }
生成微信支付的签名
/// <summary> /// 生成微信支付的签名 /// </summary> /// <param name="sparams"></param> /// <returns></returns> public static string makewxpaysign(sorteddictionary<string, string> sparams)// 生成微信支付的签名 { string key = system.configuration.configurationmanager.appsettings["wechatpaykey"]; stringbuilder sb = new stringbuilder(); foreach (keyvaluepair<string, string> temp in sparams) { if (temp.value == "" || temp.value == null || temp.key.tolower() == "sign") { continue; } sb.append(temp.key.trim() + "=" + temp.value.trim() + "&"); } sb.append("key=" + key.trim() + ""); string signkey = sb.tostring(); system.security.cryptography.md5 md5 = system.security.cryptography.md5.create(); byte[] data = md5.computehash(system.text.encoding.utf8.getbytes(signkey)); sb = new stringbuilder(); for (int n = 0; n < data.length; n++) { sb.append(data[n].tostring("x2")); } return sb.tostring().toupper(); }
生成微信支付用的js
/// <summary> /// 生成微信支付用的js /// </summary> /// <param name="openid">微信用户openid</param> /// <param name="ddbh">订单编号</param> /// <param name="je">订单总金额</param> /// <returns></returns> public static string makewxpayjs(string openid, string ddbh, string je)// 生成微信支付用的js { string rv = ""; try { conndb db = new conndb(); //获取订单编号相关
string appid = system.configuration.configurationmanager.appsettings["appid"]; string mch_id = system.configuration.configurationmanager.appsettings["wechatpaynum"]; string nonce_str = creatennonce_str(); string ip = "127.0.0.1"; //ddbh = "2018062500014"; sorteddictionary<string, string> sparams = new sorteddictionary<string, string>(); sparams.add("appid", appid); sparams.add("body", ""); sparams.add("device_info", "web"); sparams.add("mch_id", mch_id);//微信商户号 sparams.add("nonce_str", nonce_str); sparams.add("notify_url", "http://" + system.configuration.configurationmanager.appsettings["thisurl"] + "/wechat/pay/dealnotify_wx.aspx");//接收回调通知的网址 sparams.add("openid", openid);//微信用户openid sparams.add("out_trade_no", ddbh);//订单号 sparams.add("spbill_create_ip", ip);//发起者ip sparams.add("total_fee", je);//总金额 sparams.add("trade_type", "jsapi"); sparams.add("sign", makewxpaysign(sparams)); stringbuilder sb = new stringbuilder(); sb.append("<xml>"); foreach (keyvaluepair<string, string> temp in sparams) { if (temp.value == "" || temp.value == null) continue; sb.append("<" + temp.key.trim() + ">"); sb.append(temp.value.trim()); sb.append("</" + temp.key.trim() + ">"); } sb.append("</xml>"); rv = getpage("https://api.mch.weixin.qq.com/pay/unifiedorder", sb.tostring()); datatable dt = dataxml.cxmltodataset(rv).tables[0]; string prepay_id = dt.rows[0]["prepay_id"].tostring(); string timestamp = createntimestamp().tostring(); sparams = new sorteddictionary<string, string>(); sparams.add("appid", appid); sparams.add("timestamp", timestamp); sparams.add("noncestr", nonce_str); sparams.add("package", "prepay_id=" + prepay_id); sparams.add("signtype", "md5"); string getbrandwcpayrequest = "'appid' : '" + appid + "','timestamp': '" + timestamp + "','noncestr' : '" + nonce_str + "','package' : 'prepay_id=" + prepay_id + "','signtype' : 'md5','paysign' : '" + makewxpaysign(sparams) + "'"; //修改支付记录状态 return @" <script> function onbridgeready(){ weixinjsbridge.invoke( 'getbrandwcpayrequest', {" + getbrandwcpayrequest + @"}, function(res){ if(res.err_msg == 'get_brand_wcpay_request:ok' ) { location='/wechat/sc_fkcg.aspx'; } //alert('res.err_msg:'+res.err_msg+' err_code:'+res.err_code+' err_desc:'+res.err_desc); } ); } function callpay() { if (typeof weixinjsbridge == 'undefined'){ if( document.addeventlistener ){ document.addeventlistener('weixinjsbridgeready', onbridgeready, false); }else if (document.attachevent){ document.attachevent('weixinjsbridgeready', onbridgeready); document.attachevent('onweixinjsbridgeready', onbridgeready); } }else{ onbridgeready(); } } </script>"; } catch (exception ex) { return "错误:" + ex.message + " " + rv; } }
微信支付回调页面
stream s = request.inputstream; int count = 0; byte[] buffer = new byte[1024]; stringbuilder sb = new stringbuilder(); while ((count = s.read(buffer, 0, 1024)) > 0) { sb.append(encoding.utf8.getstring(buffer, 0, count)); } s.flush(); s.close(); s.dispose(); sxml = sb.tostring(); datatable dt = dataxml.cxmltodataset(sxml).tables[0]; datarow dr = dt.rows[0]; if (dr["return_code"].tostring() != "success") return;//return_code不正确 sorteddictionary<string, string> sparams = new sorteddictionary<string, string>(); foreach (datacolumn dc in dt.columns) { sparams.add(dc.columnname, dr[dc.columnname].tostring()); } string sign = assclass.makewxpaysign(sparams); if (sign != dr["sign"].tostring()) return;//签名验证失败,该数据可能并非来自微信官方 string ddbh = dr["out_trade_no"].tostring(); string tname, tid; if (dr["result_code"].tostring() == "success")//支付成功 { } else//支付失败 { } db.editdatabase(sql); response.write("<xml><return_code><![cdata[success]]></return_code><return_msg><![cdata[ok]]></return_msg></xml>");//通知微信已成功接受到通知
补充一个公众号引导页面
string appid = system.configuration.configurationmanager.appsettings["appid"]; string appsecret = system.configuration.configurationmanager.appsettings["appsecret"]; protected void page_load(object sender, eventargs e) { if (!ispostback) { if (!string.isnullorempty(request.querystring["code"])) { if (ck.getcookies("openid") == null || ck.getcookies("openid") == "") { string code = request.querystring["code"].tostring(); oauth_token model = get_token(code);//获得token oauthuser oauthuser_model = get_userinfo(model.access_token, model.openid); ck.setcookies("openid", oauthuser_model.openid, 5); ck.setcookies("nickname", oauthuser_model.nickname, 5); ck.setcookies("headimgurl", oauthuser_model.headimgurl, 5); } string openid = ck.getcookies("openid"); string nickname = ck.getcookies("nickname"); string headimgurl = ck.getcookies("headimgurl"); datatable dt = db.returndatatable("select * from bulabulabula where openid='" + openid + "'"); if (dt.rows.count == 0)//尚无该会员信息 { string newid = db.getnewid("hy"); db.editdatabase("insert into bulabulabula(*) values(" + newid + ",'" + openid + "','" + nickname + "','" + headimgurl + "',getdate())"); ck.setcookies("userid", newid, 30); ck.setcookies("username", nickname, 30); } else//已有该用户 { ck.setcookies("userid", dt.rows[0]["id"].tostring(), 30); ck.setcookies("username", dt.rows[0]["name"].tostring(), 30); } string url; if (request.querystring["pageid"] == null) { response.write("<script>alert('无跳转参数'); weixinjsbridge.call('closewindow');</script>"); return; } string pageid = request.querystring["pageid"].tostring(); switch (pageid) { case "1"://用户信息 url = "/wechat/user.aspx"; break; case "2"://其他内容 url = "/wechat/something.aspx"; break;default: response.write("<script>alert('参数异常'); weixinjsbridge.call('closewindow');</script>"); return; break; } response.redirect(url); } else { if (request.querystring["pageid"] == null) { response.write("<script>alert('无跳转参数'); weixinjsbridge.call('closewindow');</script>"); return; } string url = "url"; response.redirect(url); } } } //获得token protected oauth_token get_token(string code) { string str = assclass.getpage("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code", ""); oauth_token oauth_token_model = assclass.parsefromjson<oauth_token>(str); return oauth_token_model; } //刷新token protected oauth_token refresh_token(string refresh_token) { string str = assclass.getpage("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid + "&grant_type=refresh_token&refresh_token=" + refresh_token, ""); oauth_token oauth_token_model = assclass.parsefromjson<oauth_token>(str); return oauth_token_model; } //获得用户信息 protected oauthuser get_userinfo(string refresh_token, string openid) { // response.write("获得用户信息refresh_token:" + refresh_token + "||openid:" + openid); string str = assclass.getpage("https://api.weixin.qq.com/sns/userinfo?access_token=" + refresh_token + "&openid=" + openid, ""); oauthuser oauthuser_model = assclass.parsefromjson<oauthuser>(str); return oauthuser_model; }
上一篇: 什么是SpringBoot