
package com.yx.face.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.yx.face.boot.component.wx.WxMaConfiguration;
import com.yx.face.controller.dto.WxInfoDTO;
import com.yx.face.service.WeiXinApiService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: face-server
 * @Package: com.yx.face.service
 * @ClassName: WeiXinApiService
 * @Author: 崔哥
 * @Description:
 * @Date: 2021/11/1 18:27
 * @Version: 1.0
 */
@Service
public class WeiXinApiServiceImpl implements WeiXinApiService {
    @Value("${weixin.appid}")
    private String appid;

    @Override
    public Map<String, String> getWeiXin(WxInfoDTO dto) {
        Map<String, String> map = new HashMap<>();
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        WxMaJscode2SessionResult session = null;
        try {
            session = wxService.getUserService().getSessionInfo(dto.getCode());
        } catch (WxErrorException e) {
            e.printStackTrace();
            map.put("code", "500");
            return map;
        }
        if (session == null) {
            map.put("code", "500");
            return map;
        }
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(session.getSessionKey(), dto.getEncryptedData(), dto.getIv());
        map.put("code", "200");
        map.put("phone", phoneNoInfo.getPhoneNumber());
        map.put("openid", session.getOpenid());
        return map;
    }
}
