微信 .net 版本开发 整体比较简单
验证服务器 获取Access_token 等 都很容易
一下方法可以实现 扫一扫,分享等
让我头疼一点的是 jssdk的地方
我来介绍下我 犯过的错误
首先 获取 timestamp
用下面 这个函数
用法 :ConvertDateTimeInt(DateTime.Now).ToString(); // 时间搓
public int ConvertDateTimeInt(System.DateTime time)
{
int intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = (int)(time - startTime).TotalSeconds;
return intResult;
}
再次 noncestr
这个随机取 想怎么搞都可以
我的做法
FormsAuthentication.HashPasswordForStoringInConfigFile(DateTime.Now.toString(), "sha1").ToLower().Substring(0, 16);; //随机字符
获取 jstick 也有个错误
https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi;
type 必须是 jsapi [我写成 wx_card] 这个卡卷的
wx.config({
debug: false,
appId: 'xxxxx',
timestamp: xxxx,
nonceStr: 'xxxxx',
signature: 'xxxxxx',
jsApiList: [
'checkJsApi',
'scanQRCode',
'openProductSpecificView',
]
});
nonceStr S是大写 我是小写
下面是使用案例 (test.cshtml)
@{
Layout = null;
WXHelp w = new WXHelp();
w.Request = Request;
w.Response = Response;
string acc = w.get_Access_token("", "");
string tk = w.getapi_Tick(acc);
string fmt = "jsapi_ticket={0}&noncestr={1}×tamp={2}&url={3}";
string Timeeee = w.ConvertDateTimeInt(DateTime.Now).ToString(); // 时间搓
string sss = FormsAuthentication.HashPasswordForStoringInConfigFile(Timeeee, "sha1").ToLower(); //随机字符
string url = Request.Url.ToString();
sss = sss.Substring(0, 16);
fmt = string.Format(fmt, tk, sss, Timeeee, url);
string signature = FormsAuthentication.HashPasswordForStoringInConfigFile(fmt, "sha1").ToLower();
string nt = DateTime.Now.Ticks.ToString();
}
ad
拿来主义直接拿去用吧 需要 .net 3.5以上版本
这个是 高人封装好的 ,也许你更喜欢下面这个
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Xml;
public class WXHelp
{
public HttpRequestBase Request;
public HttpResponseBase Response;
string appid = "xxxxxxxxxxx";
string appsecret = "xxxxxxxxxxxxxxxxxx";
bool CheckSignature()
{
string signature = Request.QueryString["signature"];
string timestamp = Request.QueryString["timestamp"];
string nonce = Request.QueryString["nonce"];
//dsds
//url http://data.dodoca.com/wx/1/9b14d8cb223c6383390b38eff7ee8a3a/
string toke = "9b9edb";//token 人能够
string[] Arrtmp = { toke, timestamp, nonce };
Array.Sort(Arrtmp);
string s = string.Join("", Arrtmp);
s = FormsAuthentication.HashPasswordForStoringInConfigFile(s, "SHA1");
s = s.ToLower();
if (s == signature)
{
return true;
}
return false;
}
///
/// 调用此方法 验证
///
public void OnLoad()
{
// Writebug("访问啊");
if (string.IsNullOrEmpty(Request.QueryString["echostr"]))
{
// Writebug("写入信息");
wxmessage wx = GetWxMessage();
string temp = "";
if (wx.EventName == "subscribe")
{
temp = sendTextMessage(wx, @"回复");
}
else if (wx.Content == "1")
{
temp = sendTextMessage(wx, "你刚才输入了1恭喜恭喜");
}
else if (wx.Content == "注册")
{
temp = sendTextMessage(wx, "注册您的微信号");
}
else if (wx.Content == "")
{
temp = "没有内容";
}
Response.Write(temp);
}
else
{
Valid();
}
//
}
///
/// 获取请求过来的微信信息
///
///
private wxmessage GetWxMessage()
{
wxmessage wx = new wxmessage();
StreamReader str = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8);
XmlDocument xml = new XmlDocument();
try
{
xml.Load(str);
wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
if (wx.MsgType.Trim() == "text")
{
wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText;
}
if (wx.MsgType.Trim() == "event")
{
wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
}
}
catch (Exception e)
{
Response.Write(e.Message);
}
return wx;
}
void Valid()
{
string echoStr = Request.QueryString["echostr"].ToString();
if (CheckSignature())
{
if (!string.IsNullOrEmpty(echoStr))
{
Response.Write(echoStr);
Response.End();
}
}
}
///
/// 将c# DateTime时间格式转换为Unix时间戳格式
///
/// 时间
/// double
public int ConvertDateTimeInt(System.DateTime time)
{
int intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = (int)(time - startTime).TotalSeconds;
return intResult;
}
private dynamic getDyByName(string fnm)
{
string ss = Readbug(fnm);
if (string.IsNullOrEmpty(ss)) return null;
object boread = JsonConvert.DeserializeObject(ss); ;
dynamic dyread = boread as dynamic;
return dyread;
}
private void Writebug(string strMemo,string Fname)
{
string filename = HttpContext.Current.Server.MapPath("/App_Data/" + Fname + ".txt");
if (!Directory.Exists(HttpContext.Current.Server.MapPath("//App_Data//")))
Directory.CreateDirectory("//App_Data//");
File.Delete(filename);
using (StreamWriter sr = File.CreateText(filename))
{
try
{
sr.WriteLine(strMemo);
}
catch
{
}
}
}
private string Readbug(string Fname)
{
string radFile = "";
string filename = HttpContext.Current.Server.MapPath("/App_Data/" + Fname + ".txt");
if (!Directory.Exists(HttpContext.Current.Server.MapPath("//App_Data//")))
Directory.CreateDirectory("//App_Data//");
if (!File.Exists(filename))
{
using (File.CreateText(filename)) {
}
}
using (StreamReader sr = new StreamReader(filename))
{
try
{
radFile = sr.ReadToEnd();
}
catch
{
}
}
return radFile;
}
///
/// 发送文字消息
///
/// 获取的收发者信息
/// 笑话内容
///
private string sendTextMessage(wxmessage wx, string content)
{
string res = string.Format("{2} 0 ",
wx.FromUserName, wx.ToUserName, DateTime.Now, content);
return res;
}
private string SendPicMessage(wxmessage wx, string title, string content, string desc, string pic, string url)
{
// list.Add(string.Format("from[{0}]to[{1}]", wx.FromUserName, wx.ToUserName));
string res = string.Format(@"
{2}
1
-
", wx.FromUserName, wx.ToUserName, DateTime.Now, title, desc, pic, url);
return res;
}
public string get_Access_token(string appid, string AppSecret)
{
appid = this.appid;
AppSecret = this.appsecret;
string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
string token = "";
dynamic dyread = getDyByName("access_token");
if (dyread == null || dyread.extime < ConvertDateTimeInt(DateTime.Now)) {
string respHtml = getResponseGet(string.Format(url, appid, AppSecret));
object bo = JsonConvert.DeserializeObject(respHtml); ;
dynamic glossaryEntry = bo as dynamic;
if (glossaryEntry.access_token != null) {
glossaryEntry.extime = ConvertDateTimeInt(DateTime.Now) + 7000;
string writehtml = JsonConvert.SerializeObject(glossaryEntry);
Writebug(writehtml, "access_token");
}
}
else
{
token = dyread.access_token;
return token;
}
return token;
}
static string getResponsePost(string url)
{
return getResponse(url, "POST");
}
static string getResponseGet(string url)
{
return getResponse(url, "GET");
}
///
/// 获取返回信息
///
///
///
///
static string getResponse(string url,string pg)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = pg;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
string respHtml = sr.ReadToEnd();
return respHtml;
}
///
/// 网页 授权 获取微信ID 第一步
///
///
///
public string getCode1(string bkurl)
{
string fmt = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=997#wechat_redirect";
bkurl = HttpContext.Current.Server.UrlEncode(bkurl);
string gogo = string.Format(fmt, this.appid, bkurl);
Response.Redirect(gogo);
return "";
}
static string userAccess_token = "";
static string userRefresh_token = "";
static DateTime userTime;
string tmpacc = "";
///
/// 返回 opid 取得微信ID
///
///
///
public string getCode2(string code) {
string fmt = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
fmt = string.Format(fmt, this.appid, this.appsecret, code);
string opid = "";
string userAccess_token = "";
dynamic dyread = getDyByName("user_access_token");
if (dyread == null || dyread.extime < ConvertDateTimeInt(DateTime.Now))
{
string respHtml = getResponseGet(fmt);
object bo = JsonConvert.DeserializeObject(respHtml); ;
dynamic glossaryEntry = bo as dynamic;
if (glossaryEntry.access_token != null)
{
userAccess_token = glossaryEntry.access_token;
opid = glossaryEntry.openid;
glossaryEntry.extime = ConvertDateTimeInt(DateTime.Now) + 7000;
string writehtml = JsonConvert.SerializeObject(glossaryEntry);
Writebug(writehtml, "user_access_token");
}
}
else
{
opid = dyread.openid;
userAccess_token = dyread.access_token;
return opid;
}
return opid;
}
///
/// 暂时无用
///
///
public string getCode2Refesh()
{
string fmt = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}";
fmt = string.Format(fmt, this.appid, userRefresh_token);
string getbk = getResponseGet(fmt);
string opid = "";
object bo = JsonConvert.DeserializeObject(getbk); ;
dynamic glossaryEntry = bo as dynamic;
if (glossaryEntry.errcode == null)
{
userAccess_token = glossaryEntry.access_token;
userRefresh_token = glossaryEntry.refresh_token;
opid = glossaryEntry.openid;
}
else
{
}
return opid;
}
///
/// 拉取用户信息
///
///
///
public string getCodeUser4(string opid)
{
string fmt = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
fmt = string.Format(string.Format(fmt, tmpacc, opid));
string name = "",opid1="";
string getbk = getResponseGet(fmt);
object bo = JsonConvert.DeserializeObject(getbk); ;
dynamic glossaryEntry = bo as dynamic;
if (glossaryEntry.errcode == null)
{
name = glossaryEntry.nickname;
opid1 = glossaryEntry.openid;
}
else
{
name = glossaryEntry.errcode;
}
return name;
}
static string api_tk = "";
static DateTime api_time;
//---------------------------------------------------------------------
///
/// api_ticket 是用于调用微信卡券JS API的临时票据,有效期为7200 秒,通过access_token 来获取。
///
///
///
public string getapi_Tick(string accto)
{
string fmt = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";
fmt = string.Format(fmt, accto);
string tk = "";
dynamic dyread = getDyByName("api_tick");
if (dyread == null || dyread.extime < ConvertDateTimeInt(DateTime.Now))
{
string respHtml = getResponseGet(fmt);
object bo = JsonConvert.DeserializeObject(respHtml); ;
dynamic glossaryEntry = bo as dynamic;
if (glossaryEntry.errcode =="0")
{
tk = glossaryEntry.ticket;
glossaryEntry.extime = ConvertDateTimeInt(DateTime.Now) + 7000;
string writehtml = JsonConvert.SerializeObject(glossaryEntry);
Writebug(writehtml, "api_tick");
}
}
else
{
tk = dyread.ticket;
return tk;
}
// ///过期
//if (passtime || string.IsNullOrEmpty(api_tk))
//{
// string getbk = getResponseGet(fmt);
// object bo = JsonConvert.DeserializeObject(getbk); ;
// dynamic glossaryEntry = bo as dynamic;
// if (glossaryEntry.errcode == "0")
// {
// api_tk = glossaryEntry.ticket;
// api_time = DateTime.Now;
// return api_tk;
// }
// else
// {
// return glossaryEntry.errcode;
// }
//}
return tk;
}
}
///
/// wxmessage 的摘要说明
///
public class wxmessage
{
string s1, s2, s3, s4, s5;
public string FromUserName
{
get { return s1; }
set { s1 = value; }
}
public string ToUserName
{
get { return s2; }
set { s2 = value; }
}
public string MsgType
{
get { return s3; }
set { s3 = value; }
}
public string EventName
{
get { return s4; }
set { s4 = value; }
}
public string Content
{
get { return s5; }
set { s5 = value; }
}
}