Today I’m going to write a series to help Net Xiaobai has realized the development of its own wechat official account step by step. First of all, I would like to thank an iron friend who has provided me with a private learning and experimental environment for free over the years (although the company has the conditions to do these things, it should be clear between the public and the private, and never use any company resources for personal hobbies, and never occupy any working time). In return, this series of technical articles is also launched by introducing a wechat official account support service developed for him for free, If you feel that this series of articles has touched and helped you, please pay attention to the official account (on the left side of this post or at the end of the article), which is not only a support for my friend, but also an encouragement for me to keep writing. Of course, there are many real life benefits on the official account.
Before formally explaining the development of official account, I would like to make a statement: in order to better help beginners get started quickly, this series of articles focus on understanding the business process without using a complex framework to implement it. Otherwise, it is easy to confuse people with the light of interface and inheritance. It is easier to understand that the business is still process oriented. Therefore, although many classes are used in the process of writing, they are basically single-layer and there is no multiple inheritance, The source code is open, so you can use it.
Today, let’s talk about the first article: how to access wechat official account. I have posted a post before, but there is only code and no detailed explanation of association steps. Today, I will make a comprehensive and detailed explanation in the way of pictures and texts.
1、 Prepare server
1. Prepare a server with internet access and configure IIS and Net running environment. I use win2008 server, IIS 7.0 Net 4.5, remember to use port 80. The wechat official account interface only recognizes port 80.
2. Prepare a registered domain name and point to the above web server address.
2、 Apply for official account
1. Application
It is recommended to apply for a service number because there are many open interfaces and focus on online services. Here, the service number is used. open https://mp.weixin.qq.com/ , click “register now” to enter the registration page, select the service number as the type, and complete the registration of the official account as prompted, as shown in the following figure:
2. Certification
After registration, wechat authentication can obtain more service interfaces, which is also the basic condition for subsequent wechat payment. After login, authentication can be carried out at the position shown below, with an annual authentication fee of 300 yuan, which can be completed in about a week, as shown in the following figure:
3. Configuration
After preparing the above procedures, you can now configure and obtain the necessary parameters for the development of official account. The first is the domain name information. If there is no such premise when obtaining various official account information, you will be prompted that you have no permission.
Through the configuration and query in the figure above, we can obtain the following important parameters, which will be used in all subsequent development:
Token
AppId
AppSecret
EncodingAESKey , if this is developed in clear text, it will not be used.
. view interface permissions
3、 Access to the backstage of official account
1. Set up Web Service Directory
There are two directories whose names cannot be changed. One is app_ The code directory is used to store the source code of all classes you write. One is the bin directory, which is used to store the compiled code of the classes you write DLL file, the same class is either source code or compiled DLL file cannot be stored repeatedly. In order to facilitate viewing and modification, I don’t use the class I wrote here DLL, which are placed in the app in the form of source code_ Code directory.
Wx directory is mainly used for various pages and source code of wechat interface development.
2. Write the necessary wechat interface parameters into the configuration file. I use the static member variables of a class here. If compiled in the future, these key information can play a good confidentiality effect. The database I use is SQL server, because on Windows system, it is the most efficient combination with operating system and IIS, and efficiency should be evaluated in everything.
QinMingConfig. The contents of the CS file are as follows:
using System;
namespace QinMing.Config
{
/// <summary>
///Summary description of config
/// </summary>
public class QinMingConfig
{
public QinMingConfig()
{
//
//Todo: add constructor logic here
//
}
/// <summary>
///SQL Server database connection string
/// </summary>
public const string DatabaseConnStr = "Data Source=sql server source;Initial Catalog=your database name;User ID=username;Password=password";
/// <summary>
///Wechat official account access parameters
/// </summary>
public const string Weixin_Token = "yourtoken";
public const string Weixin_AppId = "wx.........";
public const string Weixin_AppSecret = "e5xxxxxxxxxxxxxxxxxxx";
public const string EncodingAESKey = "J1vxxxxxxxxxxxxxxxxxxxxxxx";
/// <summary>
///Request timeout setting (in milliseconds), the default is 10 seconds.
///Note: the constant here is the default value of the parameter provided to the method, not the default timeout of all requests in the method.
/// </summary>
public const int TIME_OUT = 10000;
//The parameters used in the future will be added later
}
}
3. now enter the most important link to connect with wechat official account. First, continue to look at the previous basic setting page of official account development. Before your interface code is written and works normally, the configuration of this website is unsuccessful.
The interface page is very simple, as follows:
AccessWx. Aspx source code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AccessWx.aspx.cs" Inherits="Jjlm.AccessWx" %>
AccessWx. aspx. CS source code
using System;
using System.Web;
using System.Web.Security;
using System.IO;
using System.Xml;
using System.Text;
using QinMing.Config;
//using QinMing.WeixinMessageHandler;
//using QinMing.Tools;
namespace Jjlm
{
public partial class AccessWx: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
string postStr = "";
if (Request.HttpMethod.ToLower() == "get")
{
Valid(); // The first access will verify whether your server can be connected
}
else
{
Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
postStr = Encoding.UTF8.GetString(b);
if (!string.IsNullOrEmpty(postStr))
{
ResponseMsg(postStr);
}
}
}
/// <summary>
///Return information result (wechat information return)
/// </summary>
/// <param name="weixinXML"></param>
private void ResponseMsg(string weixinXML)
{
//Part of the reply message: your code is written here
XmlDocument doc = new XmlDocument();
doc.LoadXml(weixinXML);
XmlNodeList list = doc.GetElementsByTagName("xml");
XmlNode xn = list[0];
string FromUserName = xn. SelectSingleNode("//FromUserName"). InnerText; // Pay attention to the encrypted openid of the user
string ToUserName = xn. SelectSingleNode("//ToUserName"). InnerText; // Public micro signal original ID
string MsgType=xn.SelectSingleNode("//MsgType").InnerText;
//Save the information pushed by wechat server into log file for tracking and analyzing problems
//QinMingTools. Writelog ("official account push content", convertxmltostring (DOC));
if(MsgType == "text")
{
//Text message processing part
}
else if(MsgType == "image")
{
//Picture message processing part
}
else if(MsgType == "voice")
{
//Voice message processing part
}
else if(MsgType == "video")
{
//Video message processing part
}
else if(MsgType == "shortvideo")
{
//Small video message processing part
}
else if(MsgType == "location")
{
//The location message processing part, different from the location message in the event, refers to that the user actively sends the location to the official account, which is explained in a special chapter
}
else if(MsgType == "link")
{
//Link message processing section
}
else if(MsgType == "event")
{
//Event message processing part
string Event = xn.SelectSingleNode("//Event").InnerText;
if(Event == "LOCATION")
{
//Location message processing
}
else if(Event == "CLICK")
{
//Click menu message processing
}
else if(Event == "VIEW")
{
//Action processing triggered when opening menu link
}
else
{
//Other types of message processing, such as paying attention to official account, canceling attention, scanning QR code with parameters
}
}
}
/// <summary>
///Convert XmlDocument to string
/// </summary>
/// <param name="xmlDoc"></param>
/// <returns></returns>
public string ConvertXmlToString(XmlDocument xmlDoc)
{
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, null);
writer.Formatting = Formatting.Indented;
xmlDoc.Save(writer);
StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
stream.Position = 0;
string xmlString = sr.ReadToEnd();
sr.Close();
stream.Close();
return xmlString;
}
/// <summary>
///Verify wechat signature
/// </summary>
///* sort the token, timestamp and nonce parameters in dictionary order
///* splice three parameter strings into one string for SHA1 encryption
///* the encrypted string obtained by the developer can be compared with signature to identify that the request comes from wechat.
/// <returns></returns>
private bool CheckSignature()
{
string signature = Request.QueryString["signature"].ToString();
string timestamp = Request.QueryString["timestamp"].ToString();
string nonce = Request.QueryString["nonce"].ToString();
string[] ArrTmp = { QinMingConfig.Weixin_Token, timestamp, nonce };
Array. Sort(ArrTmp); // Dictionary sorting
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
if (tmpStr.Equals(signature))
{
return true;
}
else
{
return false;
}
}
/// <summary>
///Verification when accessing wechat background for the first time
/// </summary>
private void Valid()
{
string echoStr = Request.QueryString["echoStr"].ToString();
if (CheckSignature())
{
if (!string.IsNullOrEmpty(echoStr))
{
Response.Write(echoStr);
Response.End();
}
}
}
}
}
So far, your server has completed docking with the background of wechat official account. You can use many interface functions. Have you got it? If you feel you have gained, please give me a compliment. The next chapter introduces text message processing. Please pay attention.