欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > HTML >内容正文

HTML

微信—前端获取openId方法和步骤

发布时间:2024/1/1 HTML 65 豆豆
生活随笔 收集整理的这篇文章主要介绍了 微信—前端获取openId方法和步骤 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

执行流程
前端 --> 后端服务 --> 微信服务(openId/UnionID)
微信公众号网页开发授权:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0

<template><div></div> </template><script> export default {name: 'Index',data () {return {}},created () {this.getCode()},// ***放main.js中;放入口文件中methods: {getCode () { // 非静默授权,第一次有弹框const code = getUrlParam('code') // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openIdconst local = window.location.hrefif (code == null || code === '') {window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + window.APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'} else {this.getOpenId(code) //把code传给后台获取用户信息}},getOpenId (code) { // 通过code获取 openId等用户信息,/api/user/wechat/login 为后台接口let _this = this// 后端接口实现:获取code后,请求以下连接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_codethis.$http.post('/api/user/wechat/login', {code: code}).then((res) => {let datas = res.data/* // 前端--> 应用后台 --> 微信后台{"access_token": "ACCESS_TOKEN","expires_in": 7200,"refresh_token": "REFRESH_TOKEN","openid": "OPENID","scope": "SCOPE"}*/ if (datas.code === 0 ) {console.log('成功')}}).catch((error) => {console.log(error)})},getUrlParam (name) { // 获取url指定参数var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') // 构造一个含有目标的正则表达式对象var r = window.location.search.substr(1).match(reg) // 匹配目标参数if (r != null) return unescape(r[2])return null // 返回参数值}} } </script><style lang="less" scoped></style>

微信h5静默、非静默授权获取用户openId的方法和步骤https://blog.csdn.net/qq_35430000/article/details/79299529

解决微信授权成功后点击按返回键出现空白页和报错的问题https://blog.csdn.net/qq_35430000/article/details/79299529

总结

以上是生活随笔为你收集整理的微信—前端获取openId方法和步骤的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。