微信接入官方文档是php的,网上被抄好几遍的代码是c#的,就是没vb的。今天我把这个坑填了,做vb版的接入认证。

首先是照着开发文档把微信接入的模型写好。在Models文件夹新建一个Model

Public Class WeChatRequestModel
''' <summary>
''' 加密签名
''' </summary>
Public Property signature$
''' <summary>
''' 时间戳
''' </summary>
Public Property timestamp$
''' <summary>
''' 随机数
''' </summary>
Public Property nonce$
''' <summary>
''' 用于传回的随机字符串
''' </summary>
Public Property echostr$
End Class

模型建立完成之后,新建个Controller。

微信认证是把nonce,Token,timestamp排序,然后算SHA1与signature比较。Token作为一个字符串常量,根据申请时填写的Token编写。

Const Token = "你申请的Token"

剩下的代码就是把那个php代码翻译一下,注意不要用过时的成员比如FormsAuthentication,免得以后迁移到asp.net core要重写代码:

     Private Function SHA1$(str$)
Return BitConverter.ToString(System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", "")
End Function
Private Function CheckSignature(data As WeChatRequestModel) As Boolean
Return data.signature = SHA1(String.Join("", Aggregate s In {data.nonce, Token, data.timestamp} Order By s Into ToArray)).ToLower()
End Function
<HttpGet>
Public Sub Authenticate(data As WeChatRequestModel)
If CheckSignature(data) AndAlso Not String.IsNullOrEmpty(data.echostr) Then
Response.Write(data.echostr)
Response.End()
End If
End Sub

编辑路由设定, 把模板里面带的用不上的主页路由去掉,换成微信接入认证的

Public Module RouteConfig
Public Sub RegisterRoutes(routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}") routes.MapRoute(
name:="Authenticate",
url:="{controller}/{action}/{id}",
defaults:=New With {.controller = "Home", .action = "Authenticate", .id = UrlParameter.Optional}
)
End Sub
End Module

这样修改后,只要填写Url的时候写上

你的域名/Home/Authenticate

然后把Token之类的东西写上就行了。

05-11 18:02