search
HomeBackend DevelopmentC#.Net TutorialASP.NET WeChat public account viewing fan information interface

The example in this article shares the ASP.NET WeChat fan information interface viewing code for your reference. The specific content is as follows

WeChat Token entity class:

/// <summary>
/// 微信Token实体类
/// </summary>
public class WeChatTokenEntity
{
public string Access_token { get; set; }
 
public string Expires_in { get; set; }
}

User information entity class

/// <summary>
/// 用户实体信息类
/// </summary>
public class WeChatUserEntity
{
public string Subscribe { get; set; }
 
public string Openid { get; set; }
 
public string Nickname { get; set; }
 
public string Sex { get; set; }
 
public string City { get; set; }
 
public string Province { get; set; }
 
public string Country { get; set; }
 
public string HeadImgUrl { get; set; }
 
public string Subscribe_time { get; set; }
 
public string Language { get; set; }
}

WeChat auxiliary operation Class

public class WeChatDemo
{
/*
 * 步骤:
 * 1.通过appid和secret请求微信url,得到token
 * 2.通过access_token和openid得到用户信息(头像地址等)
 * 3.通过access_token和media_id得到用户发送的微信消息
 *
 */
 
 
string appId = "wxxxxxxxxxxxxxx";
string appSecret = "1234567890-==687";
 
string wechatUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
 
 
public WeChatDemo()
{
 
}
 
/// <summary>
/// 获取token信息
/// </summary>
/// <returns></returns>
public WeChatTokenEntity GetWechatToken()
{
 //请求的url地址
 string tokenUrl = string.Format(wechatUrl, appId, appSecret);
 WeChatTokenEntity myToken;
 
 try
 {
 //声明并实例化一个WebClient对象
 WebClient client = new WebClient();
 //从执行url下载数据
 byte[] pageData = client.DownloadData(tokenUrl);
 //把原始数据的byte数组转为字符串
 string jsonStr = Encoding.Default.GetString(pageData);
 //初始化一个JavaScriptSerializer json解析器
 //序列化注意:需要引用System.Web.Extensions
 JavaScriptSerializer jss = new JavaScriptSerializer();
 //将字符串反序列化为Token对象
 myToken = jss.Deserialize<WeChatTokenEntity>(jsonStr);
 }
 catch (WebException ex)
 {
 throw ex;
 }
 catch (Exception ex)
 {
 throw ex;
 }
 
 return myToken;
}
 
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="accessToken"></param>
/// <param name="openId"></param>
/// <returns></returns>
public WeChatUserEntity GetUserIfo(string accessToken, string openId)
{
 WeChatUserEntity wue = new WeChatUserEntity();
 
 string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}";
 
 url = string.Format(url, accessToken, openId);
 
 try
 {
 WebClient wc = new WebClient();
 byte[] pageData = wc.DownloadData(url);
 string jsonStr = Encoding.UTF8.GetString(pageData);
 JavaScriptSerializer jss = new JavaScriptSerializer();
 wue = jss.Deserialize<WeChatUserEntity>(jsonStr);
 
 }
 catch (WebException ex)
 {
 throw ex;
 }
 catch (Exception ex)
 {
 throw ex;
 }
 
 return wue;
}
 
public string GetVoice(string accessToken, string mediaId)
{
 string voiceAddress = string.Empty;
 string voiceUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}";
 voiceUrl = string.Format(voiceUrl, accessToken, mediaId);
 
 WebClient wc = new WebClient();
 byte[] pageData = wc.DownloadData(voiceUrl);
 string jsonStr = Encoding.UTF8.GetString(pageData);
 
 //TODO:获取声音
 voiceAddress = jsonStr;
 
 return voiceAddress;
}
 
/// <summary>
/// 时间戳转为当前时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public DateTime TimeStamp2DateTime(string timeStamp)
{
 DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
 long time = long.Parse(timeStamp + "0000000");
 TimeSpan toNow = new TimeSpan(time);
 return dtStart.Add(toNow);
}
 
}

Main program:

class Program
{
static void Main(string[] args)
{
 WeChatDemo wcd = new WeChatDemo();
 WeChatTokenEntity wte = wcd.GetWechatToken();
 string token = wte.Access_token;
 string openId = "ogNVpt52xxxxxxxxxxxxxxxxxx";
 
 Console.WriteLine("第一步:获得access_token:\n " + token + "\n");
 
 Console.WriteLine("第二步:获得用户信息");
 WeChatUserEntity user = wcd.GetUserIfo(token, openId);
 
 Console.WriteLine("\n昵称:" + user.Nickname);
 Console.WriteLine("国家:" + user.Country);
 Console.WriteLine("省份:" + user.Province);
 Console.WriteLine("城市:" + user.City);
 Console.WriteLine("语言:" + user.Language);
 Console.WriteLine("性别:" + user.Sex);
 Console.WriteLine("OpenId:" + user.Openid);
 Console.WriteLine("是否订阅:" + user.Subscribe);
 Console.WriteLine("时间:" + wcd.TimeStamp2DateTime(user.Subscribe_time));
 Console.WriteLine("头像地址:" + user.HeadImgUrl);
 
 Console.WriteLine("\n第三步:获取微信声音地址");
 string mediaId = "vwvnskvsldkvmsdlvkmdslkvmsld";
 
 string voiceAddress = wcd.GetVoice(token, mediaId);
 Console.WriteLine("声音地址:" + voiceAddress);
 Console.Read();
}
}

The running result is as shown in the figure:

ASP.NET WeChat public account viewing fan information interface

The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I hope everyone will support PHP. Chinese website.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use