当前位置:网站首页>Example: use C # NET teaches you to do WeChat official account development (7) -- location message for general message processing.
Example: use C # NET teaches you to do WeChat official account development (7) -- location message for general message processing.
2022-04-21 13:40:00 【Chaos scar】
Today, let's talk about a very important news :GPS Location message .
One 、 Application, for example,
There are too many location-based applications , such as :
Look for people nearby ;
Find nearby merchants ;
Calculate the distance from the designated person or merchant ;
Use Baidu map 、 Tencent map 、 Ali map api Interface , Mark on the map , Realize visual map ;
Calculate the distribution fee, etc .
Two 、 How to obtain wechat user location information
WeChat official account can get WeChat users in two ways. GPS Location ,
First, common message mode , User in wechat app Active location information is sent to the official account. , As shown in the figure below :

Second, wechat app Automatically remind wechat users whether to upload location information , After the user allows , You can send location information to official account regularly. , As shown in the figure below :

This method requires interface authority to be configured in the official account of WeChat. ( See the picture below ), Turn on auto accept user information , You can choose to send every few minutes , You can also choose to send it every time you enter the official account. , Specific application needs , When there are a large number of fans , Send more frequently , The greater the server load .

The second method is explained in detail during subsequent event message processing , I won't go into that .
3、 ... and 、 Message format sent by wechat server
Location messages sent by users , After being processed by wechat server , The formation is as follows XML Send format to your server :
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1351776360</CreateTime>
<MsgType><![CDATA[location]]></MsgType>
<Location_X>23.134521</Location_X>
<Location_Y>113.358803</Location_Y>
<Scale>20</Scale>
<Label><![CDATA[ Location information ]]></Label>
<MsgId>1234567890123456</MsgId>
</xml>

Four 、 Specific implementation of the source code
After receiving the content sent by wechat server , First, the specified interface page AccessWx.aspx Identify the type of information , Then give it to the specified message processing class to process and respond . In the first of this series 1 This article introduces AccessWx.aspx.cs Introducing namespaces at the beginning of using QinMing.Weixin.MessageHandlerLocation;
And perfect the following paragraph , Add the location message processing link given in this article .
else if(MsgType == "location")
{
LocationMessageDeal tmd = new LocationMessageDeal();
Response.Write(tmd.DealResult(weixinXML));
}
In namespace QinMing.Weixin.MessageHandlerLocation Next create a new class LocationMessageDeal, It is used to process video messages sent by wechat server . Remember to put the class source code file in App_Code Under the table of contents ! The following is the location message processing source code :
QinMingWeixinMessageHandlerLocation.cs The contents of the document are as follows :
using System;
using System.Web;
using System.Xml;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using QinMing.Config;
using QinMing.Weixin.ReturnContent;
//using QinMing.WeixinSendTemplateMessage;
namespace QinMing.Weixin.MessageHandlerLocation
{
// Video message processing
public class LocationMessageDeal :System.Web.UI.Page
{
public string DealResult(string weixinXML)
{
string content = DealLocation(weixinXML);
return content;
}
public string DealLocation(string weixinXML)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(weixinXML);
XmlNodeList list = doc.GetElementsByTagName("xml");
XmlNode xn = list[0];
string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText; // After paying attention to the encryption of users openid
string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText; // Public micro signal source ID
string strresponse = "";
// Users report location information by sending location to the official account.
string Latitude = xn.SelectSingleNode("//Location_X").InnerText;
string Longitude = xn.SelectSingleNode("//Location_Y").InnerText;
string ScaleW = xn.SelectSingleNode("//Scale").InnerText;
string AddrLabel = xn.SelectSingleNode("//Label").InnerText;
UpdateLocation(FromUserName, Latitude, Longitude, ScaleW, AddrLabel);
ReturnMsg rm = new ReturnMsg();
strresponse = rm.ReturnText(FromUserName, ToUserName, " Your location information has been included , If there is any change later , Please resend the location .");
// Inform the customer service staff that wechat users have updated their location
//QinMingWeixinSendTemplateMessage SendTempMsg = new QinMingWeixinSendTemplateMessage();
//SendTempMsg.SendTempMsgRemind(" Administrators openid", " Send location message to customer ", "");
return strresponse;
}
// Update the position longitude and latitude information in the wechat user table
public void UpdateLocation(string FromUserName, string Latitude, string Longitude , string ScaleW, string AddrLabel)
{
SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "update weixin_user_info set latitude='" + Latitude + "',longitude='" + Longitude + "',"
+ "precision='" + ScaleW + "',addr_label='" + AddrLabel + "' where open_id='" + FromUserName + "'";
cmd.ExecuteScalar();
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn.Dispose();
}
}
}
}
User information table used in the previous code weixin_user_info Create the statement as follows :( This table will be frequently used later , Here is the table structure )
CREATE TABLE weixin_user_info
(
open_id nvarchar(40) NULL, -- The only encoding of WeChat users in official account
nickname nvarchar(60) NULL, -- nickname
sex int NULL, -- Gender
language nvarchar(20) NULL, -- Language
city nvarchar(40) NULL, -- City
province nvarchar(60) NULL, -- Province
country nvarchar(60) NULL, -- Township
headimgurl nvarchar(400) NULL, -- Avatar image link
unionid nvarchar(60) NULL, -- official account 、 Applet 、 Unique user ID shared by web page code scanning login
remark nvarchar(20) NULL, -- remarks
groupid nvarchar(20) NULL, -- User group
subscribe_scene nvarchar(60) NULL, -- Source of concern
qr_scene nvarchar(10) NULL, -- Scan type
qr_scene_str nvarchar(100) NULL, -- Code scanning type description
remove_flag nvarchar(10) NULL, -- Cancel attention
latitude nvarchar(50) NULL, --GPS latitude
longitude nvarchar(50) NULL, --GPS longitude
precision nvarchar(50) NULL, --GPS precision
addr_label nvarchar(200) NULL, --GPS Location address description
guishu_openid nvarchar(40) NULL, -- References openid
guishu_mobile nvarchar(12) NULL, -- The mobile number of the recommender
guishu_type nvarchar(20) NULL, -- Recommended source type
join_time datetime NULL, -- Focus on time
personal_score bigint NULL -- User points
)
5、 ... and 、 One example of location information application : Calculate the meter between two longitudes and latitudes 、 Kilometer value
// Get two GPS Distance between , The unit is rice.
MapHelper mh1 = new MapHelper();
double d1 = mh1.GetDistanceMeter(Lat1, Lon1, Lat2, Lon2);
// Get two GPS Distance between , The unit is rice.
MapHelper mh2 = new MapHelper();
double d2 = mh2.GetDistanceKilometre(Lat1, Lon1, Lat2, Lon2);
Used MapHelper Class source code is as follows :
public class MapHelper
{
private const double earth_radius = 6378.137;// Earth radius
private static double rad(double d)
{
return d * Math.PI / 180.0;
}
/// <summary>
/// Calculation 2 The distance between the points
/// </summary>
/// <param name="lat1"> spot A</param>
/// <param name="lng1"> spot A</param>
/// <param name="lat2"> spot B</param>
/// <param name="lng2"> spot B</param>
/// <returns> km </returns>
public double GetDistanceKilometre(double lat1, double lng1, double lat2, double lng2)
{
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
s = s * earth_radius;
s = Math.Round(s * 10000) / 10000;
return s;
}
/// <summary>
/// Calculation 2 The distance between the points
/// </summary>
/// <param name="lat1"> spot A</param>
/// <param name="lng1"> spot A</param>
/// <param name="lat2"> spot B</param>
/// <param name="lng2"> spot B</param>
/// <returns> rice </returns>
public double GetDistanceMeter(double lat1, double lng1, double lat2, double lng2)
{
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
s = s * earth_radius;
s = Math.Round(s * 10000) / 10;
return s;
}
}
版权声明
本文为[Chaos scar]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211217280126.html
边栏推荐
- 一份很棒的外设驱动库!(基于STM32F4)
- Open mmlab / mmpose installation and use tutorial
- 2021-2022 Guangdong Vocational College Students' professional skills competition
- Idea automatically generates unit test classes
- What are the futures varieties of agricultural products?
- Longest ascending subsequence (2) (greedy + dichotomy)
- Nmap usage
- Chris LATTNER, father of llvm: the golden age of compilers
- Exercise questions and answers of quality, investment and progress control in 2022 supervision engineer examination
- Do self media and short videos. You don't have to shoot videos yourself. Dazhou teaches you a quick way to start
猜你喜欢

Feedforward neural network

Nmap usage

Huffman coding

Peking University ACM problems 1009: edge detection

json-server的使用

What kind of comfortable sports earphones are recommended

程序员爆出自己的薪资税前月薪15000

Establishment of binary tree and its cueing

Technology giants compete to enter, who can become the "number one player" of the meta universe?

Industry video super resolution new benchmark, Kwai & Dalian research, boarded CVPR 2022
随机推荐
Do self media and short videos, and don't trust those mutual relations and mutual praise
JDBC and database connection pool
HCIP之路OSPF拓展配置
Programmers burst out their salary, with a monthly salary of 15000 before tax
In office word 2016, omml2mml appears when the formula edited by word's own formula editor is transferred to MathType Solutions to XSL problems
完成数亿元融资后,毫末智行计划超百城落地城市智能驾驶产品
Work function of boost ASIO
Last online class can be "distracted" by AI analysis. Intel's emotional detection AI is on fire
Nmap usage
International logistics centralized transportation system source code, overseas warehousing cross-border transshipment system source code
Could not load dynamic library ‘libcusolver.so.11‘
通讯录的动态实现
前馈神经网络
【csnote】db异常(冗余数据、修改异常、删除异常、插入异常)
實現隨機標簽,字體大小、顏色隨機顯示
CV technical guide free knowledge planet
MySQL uses PIP and binlog2sql to install
北京大学ACM Problems 1009:Edge Detection
Reverse Polish notation
Basic practice questions and answers of economic law in 2022 primary accounting title examination