基本信息
源码名称:C# 微信扫码授权登陆
源码大小:8.36M
文件格式:.zip
开发语言:C#
更新时间:2015-11-17
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

Web.config 必须配置正确的AppId,AppKey,Redirect_uri
改开放平台AppId必须有授权过微信登录接口


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class DefaultController : Controller
    {
        public ActionResult WeChat()
        {
            string oauthAppId = ConfigurationManager.AppSettings["oauth_app_id"];
            string redirectUri = ConfigurationManager.AppSettings["Redirect_uri"];
            ActionResult result;
            if (oauthAppId == null)
            {
                result = base.Content("出错了,您尚未配置微信相关的API信息!");
            }
            else
            {
                string state = Guid.NewGuid().ToString().Replace("-", "");
                base.Session["oauth_state"] = state;
                string sendUrl = string.Concat(new string[]
				{
					"https://open.weixin.qq.com/connect/qrconnect?appid=",
					oauthAppId,
					"&redirect_uri=",
					HttpUtility.UrlEncode(redirectUri.ToLower()),
					"&response_type=code&scope=snsapi_login&state=",
					state,
					"#wechat_redirect"
				});
                result = this.Redirect(sendUrl);
            }
            return result;
        }
        public ActionResult WeChatReturnUrl(string state, string code)
        {
            ActionResult result;
            if (base.Session["oauth_state"] == null || base.Session["oauth_state"].ToString() == "" || state != base.Session["oauth_state"].ToString() || string.IsNullOrEmpty(code))
            {
                result = base.Content("出错啦,state未初始化!");
            }
            else
            {
                Dictionary<string, object> dic = WeixinHelper.get_access_token(code, state);
                if (dic == null || !dic.ContainsKey("access_token"))
                {
                    result = base.Content("错误代码:,无法获取Access Token,请检查App Key是否正确!");
                }
                else
                {
                    if (!dic.ContainsKey("openid"))
                    {
                        result = (dic.ContainsKey("errmsg") ? base.Content(string.Concat(new object[]
						{
							"errcode:",
							dic["errcode"],
							",errmsg:",
							dic["errmsg"]
						})) : base.Content("出错啦,无法获取用户授权Openid!"));
                    }
                    else
                    {
                        string accessToken = dic["access_token"].ToString();
                        string refreshToken = dic["refresh_token"].ToString();
                        string openid = dic["openid"].ToString();
                        base.Session["oauth_name"] = "webchat";
                        base.Session["oauth_access_token"] = accessToken;
                        base.Session["oauth_openid"] = openid;
                        base.Session["oauth_refresh_token"] = refreshToken;
                        result = base.Content(this.WeChatResultJson());
                    }
                }
            }
            return result;
        }
        public string WeChatResultJson()
        {
            string result;
            if (base.Session["oauth_name"] == null || base.Session["oauth_access_token"] == null || base.Session["oauth_openid"] == null)
            {
                result = "{\"ret\":\"1\", \"msg\":\"出错啦,Access Token已过期或不存在!\"}";
            }
            else
            {
                string oauthName = base.Session["oauth_name"].ToString();
                string oauthAccessToken = base.Session["oauth_access_token"].ToString();
                string oauthOpenid = base.Session["oauth_openid"].ToString();
                string oauthRefreshToken = base.Session["oauth_refresh_token"].ToString();
                if (!WeixinHelper.check_access_token(oauthAccessToken))
                {
                    Dictionary<string, object> dic = WeixinHelper.get_refresh_token(oauthRefreshToken);
                    if (dic == null || !dic.ContainsKey("access_token"))
                    {
                        result = "{\"openid\":\"0\", \"msg\":\"出错啦,无法获取access_token!\"}";
                        return result;
                    }
                    oauthAccessToken = dic["access_token"].ToString();
                }
                Dictionary<string, object> dic2 = WeixinHelper.get_user_info(oauthAccessToken, oauthOpenid);
                if (dic2 == null)
                {
                    result = "{\"openid\":\"0\", \"msg\":\"出错啦,无法获取授权用户信息!\"}";
                }
                else
                {
                    try
                    {
                        StringBuilder str = new StringBuilder();
                        str.Append("{");
                        str.Append("\"openid\": \""   dic2["openid"]   "\", ");
                        str.Append("\"nickname\": \""   dic2["nickname"]   "\", ");
                        str.Append("\"sex\": \""   dic2["sex"]   "\", ");
                        str.Append("\"province\": \""   dic2["province"]   "\", ");
                        str.Append("\"city\": \""   dic2["city"]   "\", ");
                        str.Append("\"country\": \""   dic2["country"]   "\", ");
                        str.Append("\"headimgurl\": \""   dic2["headimgurl"]   "\", ");
                        str.Append("\"privilege\": \""   dic2["privilege"]   "\", ");
                        str.Append("\"unionid\": \""   dic2["unionid"]   "\"");
                        str.Append("\"oauth_name\": \""   oauthName   "\"");
                        str.Append("\"oauth_access_token\": \""   oauthAccessToken   "\"");
                        str.Append("\"oauth_openid\": \""   oauthOpenid   "\"");
                        str.Append("}");
                        result = str.ToString();
                    }
                    catch
                    {
                        result = "{\"ret\":\"0\", \"msg\":\"出错啦,无法获取授权用户信息!\"}";
                    }
                }
            }
            return result;
        }
    }
}