VB.NET 自动发布微信公众号内容
注册微信公众号
具体内容略
后台设置
公众号和小程序均使用AppID和AppSecret调用本接口来获取access_token。
进入微信公众号后台,设置与开发->开发接口管理->基本配置。获取AppID,创建AppSecret(只显示一次,注意保留信息)。
同时创建IP白名单,将本机公网IP地址添加到白名单内。
开发文档
https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
根据开发文档编写程序。
程序编写
界面大致如下:
引用NuGet包:Newtonsoft.Json和System.Net.Http
获取 Access token
第一步获取token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
''' <summary> ''' access_token 响应类 ''' </summary> Public Class TokenResponse Public Property access_token As String Public Property expires_in As Integer Public Property errcode As Integer Public Property errmsg As String End Class Dim _tokenResponse As TokenResponse ''' <summary> ''' 获取Token ''' </summary> ''' <param name="appId"></param> ''' <param name="appSecret"></param> ''' <returns></returns> Private Async Function Get_Access_token(ByVal appId As String, ByVal appSecret As String) As Task Dim url As String = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}" Using client As New HttpClient() Try Dim response As HttpResponseMessage = Await client.GetAsync(url) Dim responseBody As String = Await response.Content.ReadAsStringAsync() ' 将 JSON 字符串转换为对象 _tokenResponse = JsonConvert.DeserializeObject(Of TokenResponse)(responseBody) If _tokenResponse.errcode = 0 Then ' 请求成功 LBAccesstoken.Text = $"Access Token: {_tokenResponse.access_token}" Else ' 请求失败,显示错误信息 MessageBox.Show($"Error: {_tokenResponse.errcode} - {_tokenResponse.errmsg}") End If Catch ex As Exception MessageBox.Show($"请求时出现错误: {ex.Message}") End Try End Using End Function |
创建草稿
创建草稿,注意里面的缩略图素材ID需要通过下一步进行获取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
Public Class Content Public Property news_item As List(Of NewsItem) End Class Public Class NewsItem Public Property title As String Public Property thumb_media_id As String Public Property show_cover_pic As Integer Public Property author As String Public Property digest As String Public Property content As String Public Property url As String Public Property content_source_url As String End Class ''' <summary> ''' 创建草稿请求类 ''' </summary> Public Class DraftRequest Public Property articles As List(Of Article) End Class ''' <summary> ''' 图文消息结构 ''' </summary> Public Class Article Public Property article_type As String Public Property title As String Public Property author As String Public Property digest As String Public Property content As String Public Property content_source_url As String Public Property thumb_media_id As String Public Property need_open_comment As Integer Public Property only_fans_can_comment As Integer Public Property pic_crop_235_1 As String Public Property pic_crop_1_1 As String End Class ''' <summary> ''' 创建草稿响应类 ''' </summary> Public Class DraftResponse Public Property media_id As String Public Property errcode As Integer Public Property errmsg As String End Class ''' <summary> ''' 创建草稿 ''' </summary> ''' <param name="accessToken"></param> ''' <param name="title">标题</param> ''' <param name="author">作者</param> ''' <param name="digest">摘要</param> ''' <param name="content">内容</param> ''' <param name="thumbMediaId">缩略图素材ID</param> ''' <returns>草稿ID</returns> Private Async Function CreateDraft(ByVal accessToken As String, ByVal title As String, ByVal author As String, ByVal digest As String, ByVal content As String, ByVal thumbMediaId As String) As Task(Of String) Dim url As String = $"https://api.weixin.qq.com/cgi-bin/draft/add?access_token={accessToken}" ' 构建请求内容 Dim article As New Article With { .article_type = "news", .title = title, .author = author, .digest = digest, .content = content, .thumb_media_id = thumbMediaId } Dim requestContent As New DraftRequest With { .articles = New List(Of Article) From {article} } Dim json As String = JsonConvert.SerializeObject(requestContent) Using client As New HttpClient() Try Dim response As HttpResponseMessage = Await client.PostAsync(url, New StringContent(json, Encoding.UTF8, "application/json")) Dim responseBody As String = Await response.Content.ReadAsStringAsync() Dim draftResponse As DraftResponse = JsonConvert.DeserializeObject(Of DraftResponse)(responseBody) If draftResponse.errcode = 0 Then Return draftResponse.media_id Else MessageBox.Show($"创建草稿失败:{draftResponse.errcode} - {draftResponse.errmsg}") Return Nothing End If Catch ex As Exception MessageBox.Show($"创建草稿时出错: {ex.Message}") Return Nothing End Try End Using End Function |
获取素材ID
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
''' <summary> ''' 获取素材列表请求类 ''' </summary> Public Class MaterialListRequest Public Property type As String Public Property offset As Integer Public Property count As Integer End Class ''' <summary> ''' 获取素材列表响应类 ''' </summary> Public Class MaterialListResponse Public Property total_count As Integer Public Property item_count As Integer Public Property item As List(Of MaterialItem) Public Property errcode As Integer Public Property errmsg As String End Class Public Class MaterialItem Public Property media_id As String Public Property name As String Public Property update_time As Integer Public Property url As String Public Property content As Content End Class Public Class Content Public Property news_item As List(Of NewsItem) End Class Public Class NewsItem Public Property title As String Public Property thumb_media_id As String Public Property show_cover_pic As Integer Public Property author As String Public Property digest As String Public Property content As String Public Property url As String Public Property content_source_url As String End Class ''' <summary> ''' 获取素材列表 ''' </summary> ''' <param name="accessToken"></param> ''' <param name="materialType"></param> ''' <param name="offset"></param> ''' <param name="count"></param> ''' <returns></returns> Private Async Function GetMaterialList(ByVal accessToken As String, ByVal materialType As String, ByVal offset As Integer, ByVal count As Integer) As Task(Of MaterialListResponse) Dim url As String = $"https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={accessToken}" ' 构建请求内容 Dim requestContent As New MaterialListRequest With { .type = materialType, .offset = offset, .count = count } Dim json As String = JsonConvert.SerializeObject(requestContent) Using client As New HttpClient() Try Dim response As HttpResponseMessage = Await client.PostAsync(url, New StringContent(json, Encoding.UTF8, "application/json")) Dim responseBody As String = Await response.Content.ReadAsStringAsync() Return JsonConvert.DeserializeObject(Of MaterialListResponse)(responseBody) Catch ex As Exception MessageBox.Show($"获取素材列表时出错: {ex.Message}") Return Nothing End Try End Using End Function |
发布草稿
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
''' <summary> ''' 定义发布请求类 ''' </summary> Public Class PublishRequest Public Property media_id As String End Class ''' <summary> ''' 定义发布响应类 ''' </summary> Public Class PublishResponse Public Property errcode As Integer Public Property errmsg As String Public Property publish_id As String Public Property msg_data_id As String End Class Public Class PostData Public Property ID As String Public Property post_author As String Public Property post_date As String Public Property post_date_gmt As String Public Property post_content As String Public Property post_title As String Public Property post_excerpt As String Public Property post_status As String Public Property comment_status As String Public Property ping_status As String Public Property post_password As String Public Property post_name As String Public Property to_ping As String Public Property pinged As String Public Property post_modified As String Public Property post_modified_gmt As String Public Property post_content_filtered As String Public Property post_parent As String Public Property guid As String Public Property menu_order As String Public Property post_type As String Public Property post_mime_type As String Public Property comment_count As String End Class Public Class PostMetaData Public Property meta_id As String Public Property post_id As String Public Property meta_key As String Public Property meta_value As String End Class ''' <summary> ''' 发布草稿 ''' </summary> ''' <param name="accessToken"></param> ''' <param name="mediaId">草稿ID</param> ''' <returns></returns> Private Async Function PublishDraft(ByVal accessToken As String, ByVal mediaId As String) As Task(Of PublishResponse) Dim url As String = $"https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token={accessToken}" ' 构建请求内容 Dim requestContent As New PublishRequest With { .media_id = mediaId } Dim json As String = JsonConvert.SerializeObject(requestContent) Using client As New HttpClient() Try Dim response As HttpResponseMessage = Await client.PostAsync(url, New StringContent(json, Encoding.UTF8, "application/json")) Dim responseBody As String = Await response.Content.ReadAsStringAsync() Return JsonConvert.DeserializeObject(Of PublishResponse)(responseBody) Catch ex As Exception MessageBox.Show($"发布时出错: {ex.Message}") Return Nothing End Try End Using End Function |
主要程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Dim appId = TBappid.Text Dim appSecret = TBsecret.Text Get_Access_token(appId, appSecret) If _tokenResponse IsNot Nothing AndAlso _tokenResponse.errcode = 0 Then '创建草稿 Dim DraftID = Await CreateDraft(_tokenResponse.access_token, TBpostName.Text, TBauthor.Text, "", TBContent.Text, "UQ8T_EpCm9suvja1ESCzmQ_sb1ovlvDBxkEbtI8OUjjEcZqedOmXvuNi9czcVWWh") If DraftID IsNot Nothing Then ' 发布草稿 Dim publishResult As PublishResponse = Await PublishDraft(_tokenResponse.access_token, DraftID) If publishResult IsNot Nothing Then If publishResult.errcode = 0 Then LBResult.Text = $"发布成功!发布任务ID: {publishResult.publish_id}" Else LBResult.Text = $"发布失败:{publishResult.errcode} - {publishResult.errmsg}" End If Else LBResult.Text = "发布失败" End If End If End If |