uni.app 开发微信小程序获取公众号code以及openId

首先确定您的小程序和公众号的认证是同一个主体!

1.前端代码,当前是小程序内嵌入 web-view 服务器的html页面

1.1 https://www.***.com/h5 这个地址为服务器上的html地址

<template>
	<web-view src="https://www.****.com/h5"></web-view>
</template>
<script>
	import { publicApi } from '@/api'
	export default {
		data() {
			return {}
		},
		async onLoad(option) {
			if (option && option.openid) {
				let userInfo=uni.getStorageSync('userInfo');
				if(userInfo && Object.keys(userInfo).length && option.openid){
					let res=await publicApi().userOfficeUpdate({
						"userNo": userInfo.userNo,
						"officeId": option.openid
						})
						if(!res.hasErr){
							uni.$u.toast('数据同步成功')
							setTimeout(()=>{
								uni.redirectTo({
									url: '/pages/page/my/index'
								})
							},500)
						}
				}else{
					uni.$u.toast('数据同步失败')
				}
			}
		},
		methods: {}
	}
</script>

2 H5页面 放在服务器 通过域名  https://www.****.com/h5 可以直接访问

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>公众号信息网页授权</title>
		<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
		<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
		<script type="text/javascript">
			let url = window.location.href;
			let appId = '';//微信公众号appid
            let code=getUrlParam('code');
			function getUrlParam (name) {
			  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
			  let url = window.location.href.split('#')[0]
			  let search = url.split('?')[1]
			  if (search) {
			    var r = search.substr(0).match(reg)
			    if (r !== null) return unescape(r[2])
			    return null
			  } else {
			    return null
			  }
			}
			if (url.includes('code') && code!=null && code!=undefined) {
				console.log('ajax')
				$.ajax({//URL当前地址是请求后端接口传入code值获取公众号信息
		        	url:'',
					data:JSON.stringify({ code: getUrlParam('code') }),
					type: 'post',
					dataType: 'json',
					contentType:'application/json',
					success: function(result) {
						console.log(result)
						if(!result.hasErr && result.data){
							if (wx.miniProgram) {//回退到小程序web-view页面并带入参数回传
								wx.miniProgram.reLaunch({
									url: '/pages/page/webView/index?openid=' + result.data.openId,
									success: function() {},
									fall: function() {}
								})
							}
						}
						
					},
					error: function(err) {
						console.log(err)
					}
				})


			} else {
	
//	scope=snsapi_base为静默 不需要客户点确认授权	

window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
			}
		</script>
		<style>
			body,html{
				background: #F4F4F3;
			}
		</style>
	</head>
	
	<body>
	</body>
</html>

3.nginx服务器配置

 #小程序中业务认证域名配置文件访问路径
        location / {
                alias  /www/hiyfiles/h5/;
                index index.html index;
                try_files $uri $uri/ =404;

        }
       #访问公众号h5页面文件访问路径
        location /h5 {
                alias  /www/hiyfiles/h5/;
                index index.html index;

         }

4.小程序配置业务域名,需下载文件和配置,配置方式如上图

5.公众号配置业务域名,需下载文件和配置,配置方式如上图

5,最后 配置到公众号开发者为当前开发账号

1. 开发准备 在开始开发前,需要先进行一些准备工作: - 安装uni-app开发环境,详见uni-app官方文档; - 创建一个微信小程序开发者账号,获取小程序的AppID; - 在小程序管理后台中,开启“获取用户信息”权限和“登录”权限。 2. 登录流程 在uni-app中,可以使用uni.login()方法进行微信登录。该方法返回一个promise对象,表示登录是否成功。在登录成功后,可以使用uni.getUserInfo()方法获取用户信息。 具体的登录流程如下: - 调用uni.login()方法进行微信登录,并获取code值; - 将code值发送到后端服务器,后端服务器根据code获取到用户的openid和session_key; - 将openid和session_key存储到本地storage中,用于后续的用户认证; - 根据获取到的用户openid,可以将用户与后端系统中的用户进行关联。 3. 获取用户信息 在登录成功后,可以使用uni.getUserInfo()方法获取用户信息。该方法返回一个promise对象,表示获取用户信息是否成功。在获取成功后,可以将用户信息展示到页面上,或者将用户信息发送到后端服务器。 具体的获取用户信息流程如下: - 调用uni.getUserInfo()方法获取用户信息; - 将获取到的用户信息展示到页面上,或者将用户信息发送到后端服务器。 4. 完整代码示例 下面是一个完整的uni-app微信小程序登录开发示例代码: ``` <template> <view class="container"> <view class="userinfo"> <button @tap="login" v-if="!hasUserInfo">微信登录</button> <image :src="userInfo.avatarUrl" v-if="hasUserInfo" /> <text>{{userInfo.nickName}}</text> </view> </view> </template> <script> export default { data() { return { userInfo: {}, hasUserInfo: false } }, methods: { login() { uni.login({ success: res => { if (res.code) { // 将code发送到后端服务器 uni.request({ url: 'https://example.com/login', data: { code: res.code }, success: res => { // 将openid和session_key存储到本地storage uni.setStorageSync('openid', res.data.openid) uni.setStorageSync('session_key', res.data.session_key) } }) } else { console.log('登录失败:' + res.errMsg) } } }) }, getUserInfo() { uni.getUserInfo({ success: res => { this.userInfo = res.userInfo this.hasUserInfo = true // 将用户信息发送到后端服务器 uni.request({ url: 'https://example.com/userInfo', data: { openid: uni.getStorageSync('openid'), userInfo: res.userInfo } }) } }) } } } </script> <style> .container { display: flex; justify-content: center; align-items: center; height: 100vh; } .userinfo { display: flex; flex-direction: column; align-items: center; } </style> ``` 在上面的代码中,当用户点击“微信登录”按钮时,会调用login()方法进行微信登录,并将获取到的openid和session_key存储到本地storage中。当用户点击“获取用户信息”按钮时,会调用getUserInfo()方法获取用户信息,并将用户信息发送到后端服务器。在页面上,会根据hasUserInfo变量的值来决定是否展示用户信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑色咖啡 Ken

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值