WechatBindController.java 3.27 KB
package com.glsx.usedcar.web.api;

import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;

@RestController
@RequestMapping("/api/wechat/bind")
public class WechatBindController {
//
//    @Autowired
//    private WxMpService wxMpService;
//
//    @Autowired
//    private UserWechatBindService bindService;
//
//    // 服务号授权回调地址(需配置在服务号后台:开发→接口权限→网页授权获取用户基本信息)
//    @Value("${wx.mp.oauth2.callback-url}")
//    private String oauth2CallbackUrl;
//
//    /**
//     * 生成微信授权链接(App调用此接口获取链接后,引导用户跳转)
//     * @param userId 平台用户ID(App传入,确保绑定到当前用户)
//     * @return 微信授权链接
//     */
//    @GetMapping("/get-auth-url")
//    public String getAuthUrl(@RequestParam Long userId) {
//        // 1. 生成state参数(携带用户ID,防止CSRF,回调时校验)
//        String state = "bind_" + userId;
//        // 2. 构造授权链接(snsapi_base 静默授权,仅获取OpenID,无需用户确认)
//        String authUrl = wxMpService.oauth2buildAuthorizationUrl(
//                oauth2CallbackUrl,
//                "snsapi_base",
//                URLEncoder.encode(state)
//        );
//        return authUrl;
//    }
//
//    /**
//     * 微信授权回调接口(服务号后台配置的回调地址)
//     */
//    @GetMapping("/oauth2-callback")
//    public String oauth2Callback(@RequestParam String code, @RequestParam String state) {
//        try {
//            // 1. 解析state中的用户ID
//            if (!state.startsWith("bind_")) {
//                return "授权失败:无效的state参数";
//            }
//            Long userId = Long.valueOf(state.split("_")[1]);
//
//            // 2. 用code换取OpenID(snsapi_base授权仅返回OpenID)
//            WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
//            String openid = accessToken.getOpenid();
//
//            // 3. 绑定用户ID与OpenID(更新或新增绑定关系)
//            bindService.bindUserWechat(userId, openid);
//
//            // 4. 授权成功后跳转回App(通过App Scheme,如:carapp://wechat/bind/success)
//            return "<script>window.location.href='carapp://wechat/bind/success?status=1';</script>";
//        } catch (Exception e) {
//            e.printStackTrace();
//            // 授权失败跳转回App
//            return "<script>window.location.href='carapp://wechat/bind/fail?msg=" + e.getMessage() + "';</script>";
//        }
//    }
//
//    /**
//     * 查询用户绑定状态(App用于展示“已绑定”/“未绑定”)
//     */
//    @GetMapping("/status")
//    public Result<BindStatusVO> getBindStatus(@RequestParam Long userId) {
//        BindStatusVO status = bindService.getBindStatus(userId);
//        return Result.success(status);
//    }
}