微信公眾平台獲取用戶openid


首先需要一個域名,如花生殼域名,然后在微信公眾平台配置,注意,正式環境下必須要備案好了的域名,測試環境下沒有關系,先公眾號功能設置:》接口權限中的網頁授權獲取用戶基本信息》注冊一個測試者賬號,進行設置,也要修改網頁授權獲取用戶基本信息

public ActionResult Index(string id, string code, string state)
        {
            if (string.IsNullOrEmpty(id))
                return HttpNotFound();
//1.如果state為空,則跳轉至微信授權頁
            if (string.IsNullOrEmpty(state))
            {
                var redirUrl = $"http://{SiteHelper.SiteHost}/r/{id}";
                var url = "https://open.weixin.qq.com/connect/oauth2/authorize";
                url += $"?appid={SiteHelper.WeiXinAppId}&redirect_uri={HttpUtility.UrlEncode(redirUrl)}&response_type=code&scope=snsapi_userinfo&state={HttpUtility.UrlEncode(id)}#wechat_redirect";               
                return Redirect(url);
            }
        //
SiteHelper.SiteHost 是域名
        //SiteHelper.WeiXinAppId為appID 
//SiteHelper.WeiXinAppSecret為 appsecret

  //2.根據code取到用戶信息

if (string.IsNullOrEmpty(code)) return Redirect(idUrl);

var dataUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
dataUrl
+= $"?appid={SiteHelper.WeiXinAppId}&secret={SiteHelper.WeiXinAppSecret}&code={code}&grant_type=authorization_code";

var accessToken = HttpHelper.GetData(dataUrl);

var token = JsonHelper.JsonDeserialize<AccessToken>(accessToken);
if (string.IsNullOrEmpty(token?.openid)) return Redirect(idUrl);

//3.根據openid取到用戶信息。沒有則生成未關注的member

var member = Biz.Member.GetModelOrCreateNew(token.openid, token.unionid);

//4.如果WxInfo信息為空,則根據accessToken拉取wxuserinfo信息並更新

if (string.IsNullOrEmpty(member?.MemberWxInfos?.HeadImgUrl))
{ dataUrl
= "https://api.weixin.qq.com/sns/userinfo";
dataUrl
+= $"?access_token={token.access_token}&openid={member.OpenId}&lang=zh_CN";

var userData = HttpHelper.GetData(dataUrl);

var user = JsonHelper.JsonDeserialize<Biz.Entitie.UserInfo>(userData); Biz.Member.RefreshWxInfo(member, user, true); }

//5.設置Cookie,跳轉至id頁
Biz.Member.SetLoginedCookies(member, Response);

return Redirect(idUrl); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM