本人也是刚接触微信开发不久,希望能给小白一些帮助,下面直接看代码:
项目结构图:
前台页面效果:
一、前台页面:Index.cshtml
@{
ViewBag.Title = "微信公众号自定义菜单";
}
AppID(应用ID)
AppSecret(应用密钥)
AccessToken
JSON
二、页面后台:MenuControllers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WechatPostMenu.Helper;
namespace WechatPostMenu.Controllers
{
public class MenuController : Controller
{
//
// GET: /Menu/
public ActionResult Index()
{
return View();
}
public ActionResult CreateMenu()
{
string data = Request.Form["data"];
string accessToken = Request.Form["accessToken"];
var json = HttpHelper.Post("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken, data);
return Json(json);
}
public string GetAccessToken()
{
string appID = Request.QueryString["appID"];
string appSecret = Request.QueryString["appSecret"];
string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appID, appSecret);
return HttpHelper.Get(url);
}
}
}
三、HttpHelper.cs类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Web;
namespace WechatPostMenu.Helper
{
public class HttpHelper
{
public static string Post(string url, string paramData)
{
return Post(url, paramData, Encoding.UTF8);
}
public static string Post(string url, string paramData, Encoding encoding)
{
string result;
if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
}
try
{
var wc = new WebClient();
if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Encoding = encoding;
result = wc.UploadString(url, "POST", paramData);
}
catch (Exception e)
{
throw;
}
return result;
}
public static string Get(string url)
{
return Get(url, Encoding.UTF8);
}
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
throw e;
}
}
}
}
PS:原创教程,欢迎转载,但保留版权,请于明显处标明出处:http://home.cnblogs.com/u/lishuyi/,若有疑问可直接联系我 QQ:891022171 Email:[email protected]