微信小程序openId获取

1、wx.login(Object object)

调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户在当前小程序的唯一标识(openid)、微信开放平台帐号下的唯一标识(unionid,若当前小程序已绑定到微信开放平台帐号)及本次登录的会话密钥(session_key)等。

 

2、通过code获取openId和sessionKey

pom.xml文件添加依赖

<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-miniapp</artifactId>
    <version>3.3.0</version>
</dependency>

配置类WxMaConfiguration:

package wxma.configuration;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WxMaConfiguration {
	
    /**
    *  此处appId和appSecret在配置文件配置
    */
	@Value("${info.appId}")
	private String appId;
	
	@Value("${info.appSecret}")
	private String appSecret;
	
	@Bean
	public WxMaInMemoryConfig services(){
		WxMaInMemoryConfig config = new WxMaInMemoryConfig();
		config.setAppid(appId);
		config.setSecret(appSecret);
		return config;
	}

	@Bean
    public WxMaService wxMpService() {
		WxMaService wxMaService = new WxMaServiceImpl();
		wxMaService.setWxMaConfig(services());
        return wxMaService;
    }
	
}

 

项目配置文件application.yml:

 info:
     appId: 自己的appid
     appSecret: 自己的 appSecret

WxMaController编写:

@RestController
@RequestMapping("/wxMa")
public class WeMaController {
 
    @Autowired
    private WxMaService wxMaService;
 
    @ResponseBody
    @RequestMapping(value = "/getOpenId",method = RequestMethod.GET)
    public Map<String,String> getOpenId(String code) {
        try {
				WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
				Map<String,String> map = new HashMap<>();
                map.put("openId",result.getOpenid());
				map.put("sessionKey",result.getSessionKey());
                return map;
			} catch (WxErrorException e) {
                //此处WxMaException为自定义异常
				throw new WxMaException("获取openId异常");
			}
        

    }
}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值