流程:
菜单跳转URL设置为(更改自己公众号的appid 以及设置点击按钮后跳转的地址:redirect_uri)
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5bfeba33ef3fbcc&redirect_uri=https://dreamchina.tech/&response_type=code&scope=&state=123#wechat_redirect
应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。)
获取页面的URL 并从URL中获取参数code的值 将code作为参数post 到后台,由后台发送Get请求获取用户信息:
本案例采用.NET一般处理程序实现,现献上代码
代码一:后台
//有传Json数据
if (context.Request.InputStream.Length > 0)
{
var reader = new StreamReader((context.Request.InputStream));
string data = reader.ReadToEnd();
JsonObj obj = JsonConvert.DeserializeObject<JsonObj>(data);
string code = obj.Code;
if (!string.IsNullOrEmpty(code))
{
const string appid = "wx5b3dda33ef3227a";
const string secet = "3de6f73741c66f32821ce75c93cc3443";
string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"
.Replace("APPID", appid).Replace("SECRET", secet).Replace("CODE", code);
string errorCode;
//模拟Get请求
string jsonStr = HttpHelper.GetResponse(url, out errorCode);
WxObject wxobj = JsonConvert.DeserializeObject<WxObject>(jsonStr);
string opeinid = wxobj.openid;
if (string.IsNullOrEmpty(opeinid))
{
string smg = "当前用户信息无效".ToError();
context.Response.Write(smg);
}
else
{
string smg = opeinid.ToSuccess();
context.Response.Write(smg);
}
}
else
{
string msg = "请在正规途径打开".ToError();
//未获取到Code
context.Response.Write(msg);
}
context.Response.Flush();
}
代码二:前台
app.callAjaxPost("../api/WxOAuth.ashx", data, function (result) {
if (result.msgType == "error") {
mui.alert(result.msg);
}
if (result.msgType == "success") {
setValue('IdCard', result.msg);
}
});
成功后绑定openid至Id :IdCard输入框中
完结