日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

uniCloud云開發獲取小程序用戶openid

作者:小杰學前端 更新時間: 2022-07-16 編程語言

目錄

一、介紹openid

二、openid獲取難在哪

三、云開發獲取openid


一、介紹openid

我們在區分小程序用戶時都需要用到openid,用戶openid就相當于用戶在小程序里的身份證。做為用戶的唯一標示,所以獲取到用戶openid就顯得很重要了,今天來教大家怎么樣獲取要用戶的唯一標示 openid

二、openid獲取難在哪

今天試了網上的很多方法,在真機調試的時候還是能夠獲取到的,結果一上傳代碼就獲取不到了,應該也有很多同學遇到了這個問題,所以我們應該把code值傳到后端去獲取openid,因為在前端可能會被抓包或爬取到你的appid和secret,不安全,如果放在后端獲取openid,除非你的服務器被攻擊了,不然就是安全的。

三、云開發獲取openid

1. 首先我們在 uniCloud 目錄下的 cloudfunctions 下右擊創建云函數

2. 編寫云函數

'use strict';  

exports.main = async (event, context) => {
	let appid = "wxc00000000000";//你自己的appid
	let secret = "xxxxxxxxxxxxxxxxxxxxxxxx";//你自己的appsecret
	let url =
	"https://api.weixin.qq.com/sns/jscode2session?appid=" +
	appid +
	"&secret=" +
	secret +
	"&js_code=" +
	event.code +
	"&grant_type=authorization_code";
	let res = await uniCloud.httpclient.request(
		url ,// 請求路徑,
		{
			dataType:"json"
		}
	);
	let openid = res.data.openid
	return openid
};

?注意這里的 appid 和 secret 要用你自己的

3. 客戶端調用uni.login(),用得到的code調用云函數

uni.login({
    provider: "weixin",
    success: function (res) {
	    uniCloud.callFunction({
		    name: 'openid',
		    data: {
			    code: res.code
		    },
		    success: (res) => {
			    console.log('云函數返回的值::::', res.result)	
		    },
		    fail: () => {
			    console.log('云函數調用失敗')
		    }
	    })
	},
});

4. 查看輸出

?

現在我們就成功獲取到了用戶的 openid ,摸著石頭過河太難了,都是血淚啊

原文鏈接:https://blog.csdn.net/qq_49900295/article/details/125411067

欄目分類
最近更新