公众号第三方平台开发 component_verify_ticket和accessToken的获取
就是下面这个链接
下面这里是我的处理函数
private void ResponseRequest() { //WXBizMsgCrypt 这个类是腾讯提供的,下载地址是http://mp.weixin.qq.com/wiki/static/assets/a5a22f38cb60228cb32ab61d9e4c414b.zip //这里的构造函数我自己改写了,腾讯提供的构造函数需要提供三个参数的,具体请看微信提供的示例代码 WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(); string sReqMsgSig = Request["msg_signature"]; string sReqTimeStamp = Request["timestamp"]; string sReqNonce = Request["nonce"]; string sReqData = GetPost(); LogTool.LogToDirDest(filePath, LogType.Debug, string.Format("{1} 接收到的信息:{0}", sReqData, pageUrl)); string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { LogTool.LogToDirDest(filePath, LogType.Error, string.Format("{1} 解析出错:{0}", ret, pageUrl)); } else { LogTool.LogToDirDest(filePath, LogType.Debug, string.Format("{1} 解析后的内容:{0}", sMsg, pageUrl)); var xDoc = XDocument.Parse(sMsg); List<XElement> q = (from c in xDoc.Elements() select c).ToList(); var infoType = q.Elements("InfoType").First().Value; switch (infoType) { case "component_verify_ticket": //q.Elements("ComponentVerifyTicket").First() //这里就是component_verify_ticket的值,保存起来就可以了,处理完成后在页面上输出success,通知微信服务器已经接收到ticket Response.Write("success"); Response.End(); break; case "unauthorized": //当用户取消授权的时候,微信服务器也会向这个页面发送信息,在这里做一下记录 LogTool.LogToDirDest(filePath, LogType.Debug, string.Format("{1} {0} 已取消授权", q.Elements("AuthorizerAppid").First().Value, pageUrl)); Response.End(); break; default: break; } } }
补充一下我的GetPost()函数
public string GetPost() { try { System.IO.Stream s = Request.InputStream; int count = 0; byte[] buffer = new byte[s.Length]; StringBuilder builder = new StringBuilder(); while ((count = s.Read(buffer, 0, buffer.Length)) > 0) { builder.Append(Request.ContentEncoding.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); return builder.ToString(); } catch (Exception ex) { throw ex; } }
利用上面获得的component_verify_ticket作为参数,向微信服务器发送请求即可接收到第三方平台的accessToken
/// <summary> /// 获取第三方平台access_token /// </summary> /// <param name="component_appid"></param> /// <param name="component_appsecret"></param> /// <param name="component_verify_ticket"></param> /// <returns></returns> public static ResponseComponentToken Component_token(string component_verify_ticket) { var urlFormat = "https://api.weixin.qq.com/cgi-bin/component/api_component_token"; object data = null; data = new { component_appid = Config.ServerAppID, component_appsecret = Config.ServerAppSecret, component_verify_ticket = component_verify_ticket }; return CommonJsonSend.Send<ResponseComponentToken>("", urlFormat, data, timeOut: Config.TIME_OUT); }
如果请求成功,返回的json结果示例如下:
{
"component_access_token":"61W3mEpU66027wgNZ_MhGHNQDHnFATkDa9-2llqrMBjUwxRSNPbVsMmyD-yq8wZETSoE5NQgecigDrSHkPtIYA",
"expires_in":7200
}
自己转换一下即可