Realisierung Sharing-Funktion in uniapp (APP, Applet, offizieller Account)

Realisierung Sharing-Funktion in uniapp (APP, Applet, offizieller Account)

1. Teilen auf APP-Seite

Bild Alternativtext

Das Teilen auf der App-Seite kann direkt die von uniapp gekapselte uni.share-Methode verwenden. Die App-Engine von uni-app hat die Sharing-SDKs von WeChat, QQ und Weibo gekapselt, und Entwickler können verwandte Funktionen direkt aufrufen. Es kann mit WeChat, QQ, Weibo geteilt werden, und jede soziale Plattform wird als Anbieter von Sharing-Diensten bezeichnet, dh als Anbieter. Sie können Text, Bilder, Grafikleisten, Musik, Videos und andere Formen teilen. Beachten Sie gleichzeitig, dass das Teilen als Miniprogramm auch diese API verwendet. Das heißt, in der App können Sie über diese API direkt einen Inhalt in Form eines kleinen Programms (normalerweise einer Inhaltsseite) mit WeChat-Freunden teilen. Gehen Sie direkt zum Code.

<!-- #ifdef APP-PLUS -->
<view class="item" @click="appShare('WXSceneSession')">
	<view class="iconfont icon-weixin3"></view>
	<view class="">微信好友</view>
</view>
<view class="item" @click="appShare('WXSenceTimeline')">
	<view class="iconfont icon-pengyouquan"></view>
	<view class="">微信朋友圈</view>
</view>
<!-- #endif -->


appShare(scene) {
	let that = this
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let curRoute = routes[routes.length - 1].$page.fullPath // 获取当前页面路由,也就是最后一个打开的页面路由
	uni.share({
		provider: "weixin", //分享服务提供商(即weixin|qq|sinaweibo)
		scene: scene, //场景,可取值参考下面说明。
		type: 0, //分享形式
		href: `${HTTP_IP_URL}${curRoute}&spread=${that.uid}`, //跳转链接
		title: that.storeInfo.storeName, //分享内容的标题
		summary: that.storeInfo.storeInfo, //分享内容的摘要
		imageUrl: that.storeInfo.image, //图片地址
		success: function(res) {
			that.posters = false; //成功后关闭底部弹框
		},
		fail: function(err) {
			uni.showToast({
				title: '分享失败',
				icon: 'none',
				duration: 2000
			})
			that.posters = false;
		}
	});
},

Geben Sie die Wertbeschreibung ein

Wert

veranschaulichen

Anbieter Unterstützung

0

Grafik

weixin, sinaweibo

1

Klartext

weixin, qq

2

Bild

weixin, qq

3

Musik

weixin, qq

4

Video

weixin, sinaweibo

5

Applets

weixin

Szenenwertbeschreibung

Wert

veranschaulichen

WXSceneSession

Teilen Sie die Chat-Oberfläche

WXSenceTimeline

Im Freundeskreis teilen

WXSceneFavorite

Mit WeChat-Favoriten teilen

uni.share Konfigurationsanweisungen auf verschiedenen sozialen Plattformen auf der App-Seite teilen

  1. Öffnen Sie manifest.json -> Berechtigungskonfiguration des App-Moduls, aktivieren Sie Share (share);
  2. Konfigurieren Sie die Parameter von WeChat, Weibo und QQ gemäß den folgenden Dokumenten

Aktivieren Sie in der App-SDK-Konfiguration von manifest.json „WeChat-Nachrichten und -Momente“ und füllen Sie die App-ID aus. Wenn Sie sie auf der iOS-Plattform verwenden möchten, müssen Sie einen universellen Link konfigurieren.
Bild

2. Kleine Programmfreigabe

Bild AlternativtextEs gibt zwei Arten des Teilens im Applet, eines ist das Teilen über die Kapsel in der oberen rechten Ecke, und Sie können auch eine Schaltfläche auf die Seite schreiben, um sie über open-type="share" zu teilen.

//onShareAppMessage 分享给朋友
//onShareTimeline  分享到朋友圈
// #ifdef MP
onShareAppMessage: function(res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    let that = this;
    return {
    	title:'这是标题',
    	imageUrl: '这是描述',
    	path: '/pages/goods_details/index?id=' + that.id, 
    }
},
// #endif

3. Teilen von offiziellen Konten

Bild AlternativtextDie Freigabe im offiziellen Konto muss das JS-SDK von WeChat verwenden, das direkt aus der js-Datei heruntergeladen und importiert oder über npm heruntergeladen werden kann. Das Teilen des öffentlichen Kontos ist umständlich, wir können es kapseln und den entsprechenden Titel, Link und jsapi dort übergeben, wo es verwendet werden muss, damit es einfach betrieben werden kann.

Erstellen Sie eine neue wechat.js und montieren Sie sie auf dem Prototyp von vue in main.js

// #ifdef H5
import WechatJSSDK from "@/plugin/jweixin-module/index.js";


import {
	getWechatConfig,
	wechatAuth
} from "@/api/public";
import {
	WX_AUTH,
	STATE_KEY,
	LOGINTYPE,
	BACK_URL
} from '@/config/cache';
import {
	parseQuery
} from '@/utils';
import store from '@/store';
import Cache from '@/utils/cache';

class AuthWechat {

	constructor() {
		//微信实例化对象
		this.instance = WechatJSSDK;
		//是否实例化
		this.status = false;

		this.initConfig = {};

	}
	
	isAndroid(){
		let u = navigator.userAgent;
		return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
	}
	
	signLink() {
		if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
			  	window.entryUrl = location.href.split('#')[0]
			}
		return  /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl;
	}


	/**
	 * 初始化wechat(分享配置)
	 */
	wechat() {
		return new Promise((resolve, reject) => {
			// if (this.status && !this.isAndroid()) return resolve(this.instance);
			getWechatConfig()
				.then(res => {
					this.instance.config(res.data);
					this.initConfig = res.data;
					this.status = true;
					this.instance.ready(() => {
						resolve(this.instance);
					})
				}).catch(err => {
					console.log('微信分享配置失败',err);
					this.status = false;
					reject(err);
				});
		});
	}

	/**
	 * 验证是否初始化
	 */
	verifyInstance() {
		let that = this;
		return new Promise((resolve, reject) => {
			if (that.instance === null && !that.status) {
				that.wechat().then(res => {
					resolve(that.instance);
				}).catch(() => {
					return reject();
				})
			} else {
				return resolve(that.instance);
			}
		})
	}
	// 微信公众号的共享地址
	openAddress() {
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.openAddress).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	}

    // 获取经纬度;
	location(){
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.getLocation,{type: 'wgs84'}).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	} 
	
	// 使用微信内置地图查看位置接口;
	seeLocation(config){
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.openLocation, config).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	}
	
	/**
	 * 微信支付
	 * @param {Object} config
	 */
	pay(config) {
		return new Promise((resolve, reject) => {
			this.wechat().then((wx) => { 
				this.toPromise(wx.chooseWXPay, config).then(res => {
					resolve(res);
				}).catch(res => {
					resolve(res);
				});
			}).catch(res => {
				reject(res);
			});
		});
	}
	
	toPromise(fn, config = {}) {
		return new Promise((resolve, reject) => {
			fn({
				...config,
				success(res) {
					resolve(res);
				},
				fail(err) {
					reject(err);
				},
				complete(err) {
					reject(err);
				},
				cancel(err) {
					reject(err);
				}
			});
		});
	}

	/**
	 * 自动去授权
	 */
	oAuth(snsapiBase,url) {
		if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
		const {
			code
		} = parseQuery();
		if (!code || code == uni.getStorageSync('snsapiCode')){
			return this.toAuth(snsapiBase,url);
		}else{
			if(Cache.has('snsapiKey'))
				return this.auth(code).catch(error=>{
					uni.showToast({
						title:error,
						icon:'none'
					})
				})
		}
	}

	clearAuthStatus() {

	}

	/**
	 * 授权登录获取token
	 * @param {Object} code
	 */
	auth(code) {
		return new Promise((resolve, reject) => {
			wechatAuth(code, Cache.get("spread"))
				.then(({
					data
				}) => {
					resolve(data);
					Cache.set(WX_AUTH, code);
					Cache.clear(STATE_KEY);
					// Cache.clear('spread');
					loginType && Cache.clear(LOGINTYPE);
					
				})
				.catch(reject);
		});
	}

	/**
	 * 获取跳转授权后的地址
	 * @param {Object} appId
	 */
	getAuthUrl(appId,snsapiBase,backUrl) {
		let url = `${location.origin}${backUrl}`
				if(url.indexOf('?') == -1){
							url = url+'?'
						}else{
							url = url+'&'
						}
				const redirect_uri = encodeURIComponent(
					`${url}scope=${snsapiBase}&back_url=` +
					encodeURIComponent(
						encodeURIComponent(
							uni.getStorageSync(BACK_URL) ?
							uni.getStorageSync(BACK_URL) :
							location.pathname + location.search
						)
					)
				);
				uni.removeStorageSync(BACK_URL);
				const state = encodeURIComponent(
					("" + Math.random()).split(".")[1] + "authorizestate"
				);
				uni.setStorageSync(STATE_KEY, state);
				return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
				// if(snsapiBase==='snsapi_base'){
				// 	return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
				// }else{
				// 	return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
				// }
    }
	
	/**
	 * 跳转自动登录
	 */
	toAuth(snsapiBase,backUrl) {
		let that = this;
		this.wechat().then(wx => {
			location.href = this.getAuthUrl(that.initConfig.appId,snsapiBase,backUrl);
		})
	}

	/**
	 * 绑定事件
	 * @param {Object} name 事件名
	 * @param {Object} config 参数
	 */
	wechatEvevt(name, config) {
		let that = this;
		return new Promise((resolve, reject) => {
			let configDefault = {
				fail(res) {
					if (that.instance) return reject({
						is_ready: true,
						wx: that.instance
					});
					that.verifyInstance().then(wx => {
						return reject({
							is_ready: true,
							wx: wx
						});
					})
				},
				success(res) {
					return resolve(res,2222);
				}
			};
			Object.assign(configDefault, config);
			that.wechat().then(wx => {
				if (typeof name === 'object') {
					name.forEach(item => {
						wx[item] && wx[item](configDefault)
					})
				} else {
					wx[name] && wx[name](configDefault)
				}
			})
		});
	}
	isWeixin() {
		return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
	}
}

export default new AuthWechat();
// #endif

Bei Bedarf verwenden:

// 微信分享;
	setOpenShare: function(data) {
		let that = this;
		if (that.$wechat.isWeixin()) {
			let configAppMessage = {
				desc: data.synopsis,
				title: data.title,
				link: location.href,
				imgUrl: data.img
			};
			that.$wechat.wechatEvevt(["updateAppMessageShareData", "updateTimelineShareData"],
				configAppMessage);
		}
	},

Klicken Sie auf die drei Punkte in der oberen rechten Ecke des offiziellen WeChat-Kontos, um es zu teilen, damit das setOpenShare-Ereignis im Voraus ausgeführt werden kann. Wenn Sie durch Klicken auf die Schaltfläche auf eine benutzerdefinierte Weise teilen möchten, können Sie das setOpenShare-Ereignis in den Klick einfügen Ereignis der Schaltfläche.

h5-Beispiel: CRMEB-JAVA .gitee-
Open-Source-Adresse: CRMEB-JAVA .Ich
habe es hier gesehen, klicken Sie auf den gitee-Link oben, um einen Stern zu vergeben

Supongo que te gusta

Origin blog.csdn.net/m0_67391377/article/details/123431876
Recomendado
Clasificación