黑马苍穹外卖项目笔记06_微信登录、商品浏览


一.HttpClient

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
本项目将HttpClient封装在utils工具包下的HttpClientUtil类中,以后想要发送http请求直接调用该类中的方法即可.

二.微信小程序开发

在这里插入图片描述
微信小程序开发就不用多说了,这个项目最主要关注于后端代码的实现

三.微信登录

一.需求分析和设计

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二.代码开发

1.首先配置用于请求微信接口服务所需的appid和appsecret以及JWT令牌

首先,在application.yml中:

wechat:
    appid: ${sky.wechat.appid}
    secret: ${sky.wechat.secret}

再通过dev.yml给主配置注入值

其次,配置用户登录的令牌设置:

user-secret-key: itheima
    # 设置jwt过期时间
    user-ttl: 7200000
    # 设置前端传递过来的令牌名称
    user-token-name: authentication

配置好后,就可以通过spring管理对应的bean类

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "sky.wechat")
@Data
public class WeChatProperties {

    private String appid; //小程序的appid
    private String secret; //小程序的秘钥
    private String mchid; //商户号
    private String mchSerialNo; //商户API证书的证书序列号
    private String privateKeyFilePath; //商户私钥文件
    private String apiV3Key; //证书解密的密钥
    private String weChatPayCertFilePath; //平台证书
    private String notifyUrl; //支付成功的回调地址
    private String refundNotifyUrl; //退款成功的回调地址

}
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "sky.jwt")
@Data
public class JwtProperties {

    /**
     * 管理端员工生成jwt令牌相关配置
     */
    private String adminSecretKey;
    private long adminTtl;
    private String adminTokenName;

    /**
     * 用户端微信用户生成jwt令牌相关配置
     */
    private String userSecretKey;
    private long userTtl;
    private String userTokenName;

}

2.根据接口定义创建和完善UserController的login方法

@RestController
@RequestMapping("/user/user")
@Api(tags = "C端-用户接口")
@Slf4j
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserService userService;
    /**
     * C端用户登录--微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("微信用户登录,授权码为:{}", userLoginDTO.getCode());
        User user = userService.wxLogin(userLoginDTO);

        //设置JWT令牌安全码
        Map claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }
}

3.创建UserService接口:

import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;

public interface UserService {

    /**
     * 根据微信授权码实现微信登录
     * @param userLoginDTO
     * @return
     */
    User wxLogin(UserLoginDTO userLoginDTO);
}

4.创建和完善UserServiceImpl实现类:

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    public User wxLogin(UserLoginDTO userLoginDTO) {
        //使用HttpClient发送get请求到微信接口服务,返回openid
        String code = userLoginDTO.getCode();
        String openid = getOpenid(code);
        //判断openid是否为空,为空则抛出异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //用openid查询User表,为空则自动保存
        User user = userMapper.getByOpenid(openid);

        if (user == null) {
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回User对象
        return user;
    }


    /**
     * 获取微信用户的openid
     *
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        Map map = new HashMap();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        log.info("微信登录返回结果:{}", json);

        //解析字符串
        JSONObject object = JSON.parseObject(json);
        String openid = object.getString("openid");
        log.info("微信用户的openid为:{}", openid);

        return openid;
    }
}

5.总结

代码没有难度,最重要的是在于理解新接触到的HttpClient发送请求的应用

四.商品浏览

导入代码即可,全是增删改查,想学技术的可以直接跳过;想熟练的可以自己写

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值