ASP.NET开发中调用公众号客服接口的代码展现
在官方的公众号后台是可以向用户发送信息的,当用户与官方账号进行互动的时候,微信会将消息数据发送给开发者,开大者会通过POST包向用户发送消息,下面是爱站技术频道为大家提供的ASP.NET开发中调用公众号客服接口的代码展现,一起来参考一下吧!
本文实例为大家分享了ASP.NET微信客服接口的具体代码,供大家参考,具体内容如下
Kf_account.cs代码:
public partial class Kf_account : Form { private readonly DataTable adt_user = new DataTable(); private readonly string as_INIFile = Application.StartupPath + "\\user.ini"; public Kf_account() { BindUser(); } private void BindUser() { if (!File.Exists(as_INIFile)) { var str = new StringBuilder(); str.Append(";内容由程序自动生成,请不要修改此文件内容\r\n"); str.Append("[total]\r\n"); str.Append("total=\r\n"); str.Append("[count]\r\n"); str.Append("count=\r\n"); str.Append("[user]\r\n"); //StreamWriter sw = default(StreamWriter); //sw = File.CreateText(ls_INIFile); //sw.WriteLine(str.ToString()); //sw.Close(); File.WriteAllText(as_INIFile, str.ToString(), Encoding.Unicode); File.SetAttributes(as_INIFile, FileAttributes.Hidden); } CheckForIllegalCrossThreadCalls = false; InitializeComponent(); Icon = Resource1.ico; lkl_num.Text = INIFile.ContentValue("total", "total", as_INIFile); lkl_num_c.Text = INIFile.ContentValue("count", "count", as_INIFile); pictureBox1.Visible = true; var sr = new StreamReader(as_INIFile, Encoding.Unicode); String line; int li_count = 0; adt_user.Columns.Clear(); adt_user.Columns.Add("username", Type.GetType("System.String")); adt_user.Columns.Add("openid", Type.GetType("System.String")); while ((line = sr.ReadLine()) != null) { li_count++; if (li_count > 6) { line = SysVisitor.Current.GetFormatStr(line); DataRow newRow; newRow = adt_user.NewRow(); newRow["username"] = line.Substring(0, line.LastIndexOf('=')); newRow["openid"] = line.Substring(line.LastIndexOf('=') + 1); adt_user.Rows.Add(newRow); } } sr.Close(); dataGridView1.AutoGenerateColumns = false; dataGridView1.DataSource = adt_user; //dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells; lbl_count.Text = "共" + (li_count - 6) + "行"; pictureBox1.Visible = false; } private void btn_GetUser_Click(object sender, EventArgs e) { if (MessageBox.Show(@"拉取用户信息的速度取决于你的关注数与网络速度, 可能需要几分钟甚至更长时间。 使用此功能将消耗大量用户管理接口配额。 要继续此操作吗?", "提示:", MessageBoxButtons.YesNo) == DialogResult.No) { return; } var thr = new Thread(Get_user_list); thr.Start(); } private void Get_user_list() { File.Delete(as_INIFile); var str = new StringBuilder(); str.Append(";内容由程序自动生成,请不要修改此文件内容\r\n"); str.Append("[total]\r\n"); str.Append("total=\r\n"); str.Append("[count]\r\n"); str.Append("count=\r\n"); str.Append("[user]\r\n"); File.WriteAllText(as_INIFile, str.ToString(), Encoding.Unicode); File.SetAttributes(as_INIFile, FileAttributes.Hidden); string ls_appid = INIFile.ContentValue("weixin", "Appid"); string ls_secret = INIFile.ContentValue("weixin", "AppSecret"); string access_token = ""; string menu = ""; if (ls_appid.Length != 18 || ls_secret.Length != 32) { MessageBox.Show("你的Appid或AppSecret不对,请检查后再操作"); return; } access_token = SysVisitor.Current.Get_Access_token(ls_appid, ls_secret); if (access_token == "") { MessageBox.Show("Appid或AppSecret不对,请检查后再操作"); return; } menu = SysVisitor.Current.GetPageInfo("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token); if (menu.Substring(2, 7) == "errcode") { MessageBox.Show("拉取失败,返回消息:\r\n" + menu); } JObject json = JObject.Parse(menu); lkl_num.Text = json["total"].ToString(); INIFile.SetINIString("total", "total", lkl_num.Text, as_INIFile); lkl_num_c.Text = json["count"].ToString(); INIFile.SetINIString("count", "count", lkl_num_c.Text, as_INIFile); int li_count = int.Parse(json["count"].ToString()); btn_GetUser.Enabled = false; pictureBox1.Visible = true; FileStream fs = null; Encoding encoder = Encoding.Unicode; for (int i = 0; i /// 获取用户信息详情,返回json /// /// private string Get_User(string as_openid) { string ls_json = ""; string access_token = ""; access_token = SysVisitor.Current.Get_Access_token(); ls_json = SysVisitor.Current.GetPageInfo("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + as_openid + "&lang=zh_CN"); return ls_json; } ///
private string Get_UserName(string as_openid) { string ls_json = ""; ls_json = Get_User(as_openid); string username = ""; JObject json = JObject.Parse(ls_json); username = json["nickname"].ToString(); username = SysVisitor.Current.GetFormatStr(username); return username; } private void btn_search_Click(object sender, EventArgs e) { string username = txt_search.Text.Trim(); if (string.IsNullOrWhiteSpace(username)) { return; } DataRow[] datarows = adt_user.Select("username like '%" + username + "%'"); var ldt = new DataTable(); ldt.Columns.Clear(); ldt.Columns.Add("username", Type.GetType("System.String")); ldt.Columns.Add("openid", Type.GetType("System.String")); ldt = ToDataTable(datarows); try { lbl_count.Text = ldt.Rows.Count.ToString(); } catch { } dataGridView1.AutoGenerateColumns = false; dataGridView1.DataSource = ldt; } public DataTable ToDataTable(DataRow[] rows) { if (rows == null || rows.Length == 0) return null; DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构 foreach (DataRow row in rows) tmp.Rows.Add(row.ItemArray); // 将DataRow添加到DataTable中 return tmp; } private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { try { SysVisitor.Current.Wx_openid = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value.ToString(); SysVisitor.Current.Wx_username = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString(); //MessageBox.Show(str); grb_chat.Enabled = true; grb_chat.Text = SysVisitor.Current.Wx_username; } catch { } webBrowser_msg.DocumentText = ""; string url = string.Format("https://api.weixin.qq.com/cgi-bin/customservice/getrecord?access_token={0}", SysVisitor.Current.Get_Access_token()); string ls_text = @"{"; ls_text += "\"starttime\" : " + DateTime.Now.AddDays(-3).Ticks + ","; ls_text += "\"endtime\" : " + DateTime.Now.Ticks + ","; ls_text += "\"openid\" : \"" + SysVisitor.Current.Wx_openid + "\","; ls_text += "\"pagesize\" : 1000,"; ls_text += "\"pageindex\" : 1,"; ls_text += "}"; string ls_history = SysVisitor.Current.PostPage(url, ls_text); webBrowser_msg.DocumentText = ls_history; } private void btn_send_Click(object sender, EventArgs e) { string ls_msg = richTextBox_msg.Text; string ls_text = @"{"; ls_text += "\"touser\":\"" + SysVisitor.Current.Wx_openid + "\","; ls_text += "\"msgtype\":\"text\","; ls_text += "\"text\":"; ls_text += "{"; ls_text += "\"content\":\"" + ls_msg + "\""; ls_text += "}"; ls_text += "}"; string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", SysVisitor.Current.Get_Access_token()); string ls_isright = SysVisitor.Current.PostPage(url, ls_text); webBrowser_msg.DocumentText += "
" + ls_isright + "
"; } private void btn_addkf_Click(object sender, EventArgs e) { string url = string.Format("https://api.weixin.qq.com/customservice/kfaccount/add?access_token={0}", SysVisitor.Current.Get_Access_token()); //客服账号 设置 xxx@你的公众号 这样的格式才是正确的哟。 string ls_text = "{"; ls_text += "\"kf_account\":test2@gz-sisosoft,"; ls_text += "\"nickname\":\"客服2\","; ls_text += "\"password\":\"12345\","; ls_text += "}"; string ls_kf = @"{ 'kf_account' : 'test1@gz-sisosoft', 'nickname' : '客服1', 'password' : '123456', }"; string ls_isok = SysVisitor.Current.PostPage(url, ls_text); MessageBox.Show(ls_isok); } private void Kf_account_Load(object sender, EventArgs e) { } }
SysVisitor.cs代码:
class SysVisitor { private static SysVisitor visit = null; public static SysVisitor Current { get { if (visit == null) visit = new SysVisitor(); return visit; } } ///
///appid ///appsecret ///
///Url地址 ///
///URL ///Post数据 ///
/// ///
public string Wx_username { get { return ls_username; } set { ls_username = value; } } string ls_openid = ""; ///
public string Wx_openid { get { return ls_openid; } set { ls_openid = value; } } }
INIFile.cs代码:
class INIFile { /////
/////INI文件中的段落 /////INI文件中的关键字 /////INI文件中关键字的数值 /////INI文件的完整的路径和名称 /////
/////INI文件中的段落名称 /////INI文件中的关键字 /////无法读取时候时候的缺省数值 /////读取数值 /////数值的大小 /////INI文件的完整路径和名称 //[DllImport("kernel32")] //private static extern int GetPrivateProfileString( // string section, string key, string def, StringBuilder retVal, int size, string filePath); //static string gs_FileName = System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"; /////
/////INI文件中的段落名称 /////INI文件中的关键字 /////INI文件的完整路径和名称 //public static string GetINIString(string as_section, string as_key, string as_FileName) //{ // StringBuilder temp = new StringBuilder(255); // int i = GetPrivateProfileString(as_section, as_key, "", temp, 255, as_FileName); // return temp.ToString(); //} /////
/////INI文件中的段落名称 /////INI文件中的关键字 /////INI文件的完整路径和名称 //public static string GetINIString(string as_section, string as_key) //{ // return GetINIString(as_section, as_key, gs_FileName); //} /////
/////INI文件中的段落 /////INI文件中的关键字 /////INI文件中关键字的数值 /////INI文件的完整路径和名称 //public static long SetINIString(string as_section, string as_key, string as_Value, string as_FileName) //{ // return WritePrivateProfileString(as_section, as_key, as_Value, as_FileName); //} /////
/////INI文件中的段落 /////INI文件中的关键字 /////INI文件中关键字的数值 //public static long SetINIString(string as_section, string as_key, string as_Value) //{ // return SetINIString(as_section, as_key, as_Value, gs_FileName); //} ///
///节点名称[如[TypeName]] ///键 ///值 ///文件路径 ///
///节点名称 ///键 ///值 ///
///节点名称 ///键 ///值 ///stringbulider对象 ///字节大小 ///文件路径 ///
///节点名称 ///键 ///
///节 段,欲获取的小节。注意这个字串不区分大小写 ///缓冲区 返回的是一个二进制的串,字符串之间是用"\0"分隔的 ///缓冲区的大小 ///初始化文件的名字。如没有指定完整路径名,windows就在Windows目录中查找文件 ///
///指定的段落 ///ini文件的绝对路径 ///
///要写入的段落名 ///要删除的键 ///INI文件的完整路径和文件名 public static void DelKey(string section, string key, string as_FilePath = "") { if (as_FilePath == "") { WritePrivateProfileString(section, key, null, strFilePath); } else { WritePrivateProfileString(section, key, null, as_FilePath); } } ///
public static ArrayList ReadSections() { byte[] buffer = new byte[65535]; int rel = GetPrivateProfileSectionNamesA(buffer, buffer.GetUpperBound(0), strFilePath); int iCnt, iPos; ArrayList arrayList = new ArrayList(); string tmp; if (rel > 0) { iCnt = 0; iPos = 0; for (iCnt = 0; iCnt
运行结果:
上面的文章就是爱站技术频道小编给大家介绍的ASP.NET开发中调用公众号客服接口的代码展现,想要对编程了如指掌的话,平时不妨多看看js.aizhan.com推荐的知识吧!