在小程序中获取公众号openid

1.在公众号里面配置域名

公众号->开发->开发管理->开发设置->业务域名

  1. 安装插件
{
  "dependencies": {
    "jweixin-module": "^1.6.0"
  }
}

npm install jweixin-module --save
import wx from 'jweixin-module'
Vue.prototype.$wx= wx
<template>
	<view class="content">
		
	</view>
</template>

<script>
	export default {
		data() {
			return {

			}
		},
		onLoad() {

		},
		created() {
			uni.showLoading({
				title:'加载中...'
			})
		},
		onShow() {
			this.$wx.miniProgram.reLaunch({
				url: `/mind/userInfo/userInfo?code=${this.geturlparam('code')}` //条转小程序页面
			})
		},
		methods: {
			geturlparam(code) {
				let that = this
				let url = window.location.href
				let p = url.split('?')[1]
				let params = new URLSearchParams(p);
				return params.get(code)
			}
		}
	}
</script>

<style>

</style>
<template>
	<!-- 用于获取公众号openid -->
	<view>
		<web-view @message='message' @onPostMessage='onPostMessage'  :src="`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdda6f3a9ef6c&redirect_uri=https://sysaq.zmu.edu.cn/code&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`"></web-view>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			}
		},
		methods: {
			// https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdda1c06c&redirect_uri=https://sysaq.zmu.edu.cn/code&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
		},
		onLoad(options) {
			uni.showLoading({
				title:'授权中...'
			})
		}
	}
</script>

<style>

</style>
onLoad(options){
  this.getGshOpenid(options.code);
}
	// 获取公众号openid
			getGshOpenid(code){
				uni.$u.http.post('/api/v1.UserLogin/ouath',{
					code:code
				}).then(res => {
					if(res.data.openid){
						this.gzhOpenid = res.data.openid
					}else{
						uni.showToast({
							title:'缺少必要参数,重新注册',
							icon:'error'
						})
						setTimeout(() => {
							uni.redirectTo({
								url:'/pages/index/index'
							})
						},1500)
						
					}
				})
			},

后端代码

 /**
     * 通过code 获取公众号openid
     * @return null
     */
    public function ouath()
    {
        $where = $this->request->getMore([
            ['code', ''],
        ]);
        if (!$where['code']) return $this->error('缺少必要参数');
        $appId = Filesystem::getDiskConfig('gzh', 'app_id');
        $secret = Filesystem::getDiskConfig('gzh', 'secret');
        $data = Ask::geturl('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appId . '&secret=' . $secret . '&code=' . $where['code'] . '&grant_type=authorization_code');
        return $this->success('', $data);

    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值