微信公众号 经网页授权获取用户基本信息(snsapi_userinfo)

关于snsapi_userinfo网页授权的说明

以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。

具体java后端代码如下:

getUserInfo

/**
 * 用户服务
 */
@RestController
@RequestMapping("/wx/user")
@Validated
public class WxUserController {
    private static String APPID = "你的公众号appid";
    private static String SECRET = "你的公众号secret";
    private static final long serialVersionUID = 1L;

    @Autowired
    private LitemallUserService userService;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * snsapi_userinfo为scope发起的网页授权
     * 是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
     */
    @RequestMapping("/getUserInfo")
    public Object getUserInfo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
              
### 实现微信公众号网页授权获取用户信息 为了在 ASP.NET 环境中实现微信公众号网页授权获取用户信息,需遵循特定流程。此过程涉及多个接口调用和安全验证。 #### 准备工作 确保已注册微信公众平台账号,并完成开发者模式设置。还需获得 AppID 和 AppSecret 这两个重要参数[^1]。 #### 授权登录页面重定向URL构建 当用户访问应用时,应先将其导向至微信服务器进行身份确认。为此,在 ASP.NET 应用程序中创建一个控制器方法来生成跳转链接: ```csharp public ActionResult RedirectUrl() { string appId = "your_app_id"; string redirectUri = HttpUtility.UrlEncode("http://example.com/callback"); string scope = "snsapi_userinfo"; // 或者 snsapi_base 如果只需要静默授权 string state = Guid.NewGuid().ToString(); ViewBag.AuthorizeUrl = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&redirect_uri={redirectUri}&response_type=code&scope={scope}&state={state}#wechat_redirect"; return View(); } ``` 上述代码片段展示了如何构造用于发起 OAuth 2.0 请求的 URL 地址[^2]。 #### 处理回调请求 一旦用户同意授权,则会被重定向回指定地址 (即 `redirect_uri`) 并附带 code 参数。此时可在应用程序端处理该回调请求,通过交换得到 access_token 及 openid: ```csharp public async Task<ActionResult> Callback(string code, string state) { using(var client = new HttpClient()) { var response = await client.GetAsync($"https://api.weixin.qq.com/sns/oauth2/access_token?appid=YOUR_APP_ID&secret=YOUR_APP_SECRET&code={code}&grant_type=authorization_code"); dynamic result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); string accessToken = result.access_token; string openId = result.openid; // 使用access_token和openid去拉取用户基本信息 var userInfoResponse = await client.GetAsync($"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}"); dynamic userInfoResult = JsonConvert.DeserializeObject(await userInfoResponse.Content.ReadAsStringAsync()); // 对userInfoResult中的数据做进一步处理... } return Content("success"); } ``` 这段 C# 代码实现了接收来自微信服务器返回的数据,并从中提取必要的 token 和 ID 来查询用户的公开资料[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值