H5 comparte páginas h5, applets a WeChat

1. H5 comparte la página h5 (formulario de enlace de tarjeta) a WeChat

Primero vaya a la plataforma pública de WeChat para completar el nombre de dominio de seguridad de la interfaz js

Originalmente quería usar WeChat para desarrollar js-sdk, pero no pareció funcionar durante mucho tiempo.

Descripción general | Documentación abierta de WeChat (qq.com)

Importar archivo js: http://res.wx.qq.com/open/js/jweixin-1.6.0.js

 parte del código:

Un solo h5 no puede evocar WeChat. Necesita una aplicación nativa para integrar el SDK de WeChat, la aplicación para ajustar el método de WeChat y el método de h5 para ajustar la aplicación.

Luego use el complemento: m-share

m-share: componente para compartir páginas h5, admite compartir con amigos de WeChat, Moments, Sina Weibo, Qzone y QQ. (gitee.com)

Nota: este método también se implementa con js-sdk de native+WeChat, y está muy limitado en los navegadores, solo admite qq y uc

paso uno:

Complete el nombre de dominio de seguridad de la interfaz js en la plataforma pública de WeChat

Segundo paso:

Primero vaya a instalar el complemento, porque es un proyecto uniapp y no hay un archivo package.json, así que primero vaya al directorio raíz del proyecto cmd y ejecute:

npm inicializar -y

npm instalar m-share

Paso tres:

<template>
	<view class="">
		<view><button @click="but">分享</button></view>
		<view><button @click="pyq">分享朋友圈</button></view>
	</view>
</template>

<script>
import Mshare from 'm-share';  //引入微信分享插件
export default {
	data() {
		return {
			isWechant:false  
		};
	},
	onLoad() {
		this.isWechantFun()  
		console.log(Mshare, 'Mshare',this.isWechant);
	},
    async created() {
		Mshare.init(this.getWxConfig()); //插件初始化
		if (this.isWechant) {
			this.getWxConfig();
		}
	},
	methods: {
		isWechantFun() {   //判断是否在微信环境
			var ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/MicroMessenger/i) == "micromessenger") {
				this.isWechant=true;
			} else {
				this.isWechant= false;
			}
		},
		getWxConfig() {       //Mshare.init初始化配置
			let url = location.href.split('#')[0];
			console.log(url, 'url微信分享调接口参数');
			uni.request({        //后端获取签名信息等
				url: '*****',
				method: 'POST',
				data: {
					url: location.href.split('#')[0]
				},
				success: res => {
					let result = res.data.data;
					console.log(result, '获取微信签名');
					Mshare.wxConfig({
						title: '微信分享的标题',
						desc: '微信分享的介绍详情',
						imgUrl: 'http://****',
						link:'http://***',
						wx: {
							debug: true,
							appId: result.appId,
							timestamp: result.timestamp,
							nonceStr: result.noncestr,
							signature: result.signature
						},
						infoMap: {
							wx: {
								title: '微信分享的标题',
						        desc: '微信分享的介绍详情',
						        imgUrl: 'http://****',
						        link:'http://***',
							}
						}
					});
				}
			});
		},
		
		innitConfig() {         // Mshare初始化
			let config = {
				title: '微信分享的标题',
				desc: '微信分享的介绍详情',
				imgUrl: 'http://****',
				link:'http://***',
				types: ['wx', 'wxline', 'qq', 'qzone', 'sina'],
				infoMap: {
					wx: {
						title: '微信分享的标题',
						desc: '微信分享的介绍详情',
						imgUrl: 'http://****',
						link:'http://***',
					}
				},
				fnDoShare(type) {
					console.log('分享回调:', type);
				}
			};
			return config;
		},

		but() {    //点击分享
			Mshare.to('wx', this.innitConfig());   //分享到微信聊天
			 	// Mshare.to('wxline', this.innitConfig());   //分享到微信朋友圈
		} 
	}
};
</script>

<style></style>

Se puede dividir en dos situaciones: 1: Compartir en el navegador evocará el cuadro de compartir: el éxito de compartir tendrá la forma de una tarjeta; 2: Abrir en WeChat solo guiará al usuario a hacer clic en tres puntos para compartir: el compartir el éxito será en forma de enlace (valor de enlace)

Si es una aplicación, use la API oficial proporcionada por uniapp: uni.share

const ShareWXSenceTimeline = (data) => {
		// 微信朋友圈分享
		// #ifdef H5
		vm.$u.toast('H5暂不支持分享功能')
		return
		// #endif
		// #ifdef H5
		uni.share({
			provider: "weixin",
			type: 0,
			scene: "WXSenceTimeline",
			href: ,  //链接
			title: this.title,//标题
			summary:this.title,//内容
			imageUrl:this.company_logo,//图片
			success() {
				// 分享完成,请注意此时不一定是成功分享
				uni.hideLoading()
			},
			fail(e) {
				uni.hideLoading()
				// 分享失败
				uni.showModal({
					title: '提示',
					content: e.msg || '分享失败',
					showCancel: false,
					cancelText: '',
					confirmText: '确定',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			}
		})
		// #endif
	}

2. Subprograma H5 para compartir en WeChat (subprograma de llamada)

Primero determine en qué navegador se encuentra:

		isWx() {
			//判断是否为微信
			var ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				return true;
			}
			return false;
		},

1) En el navegador WeChat

Directorio | Documentación abierta de WeChat (qq.com)

Primero inyecte el permiso de WeChat y llámelo onload 

		getWxConfig() {
			uni.request({
				url: 'https:/*****************',
				method: 'POST',
				data: {
					url: location.href.split('#')[0]
				},
				success: res => {
					let result = res.data.data;
					console.log('result', result, {
						debug: false,
						appId: result.appId,
						timestamp: result.timestamp,
						nonceStr: result.noncestr,
						signature: result.signature,
						jsApiList: ['scanQRCode', 'updateAppMessageShareData', 'updateTimelineShareData'], // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
						openTagList: ['wx-open-launch-weapp']
					});
					wx.config({
						debug: false,
						appId: result.appId,
						timestamp: result.timestamp,
						nonceStr: result.noncestr,
						signature: result.signature,
						jsApiList: ['scanQRCode', 'updateAppMessageShareData', 'updateTimelineShareData'], // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
						openTagList: ['wx-open-launch-weapp']
					});

					wx.ready(function() {
						console.log('ready');
					});
				}
			});
		},

Vistas y Eventos 

this.wxPath = 'pages/homepage/home?label_no=' + this.label_no;

--------------------------------------------


<div class="btn active" v-bind:class="{ Taa: isclass }" v-if="isWx()">
						<wx-open-launch-weapp
							id="launch-weapp"
							username="gh_********"
							:path="wxPath"
							@launch="onLaunch"
							@error="onError"
						>
							<script type="text/wxtag-template">
									<div  class='wxbtn'>
										进入房间
									</div>
								<style>
									.wxbtn{
										color:#fff;
										line-height:33px;
									font-size:20px;
									margin:5px 0;
									}
								</style>
							</script>
						</wx-open-launch-weapp>
					</div>

-----------------------------------------------

		onLaunch() {
			alert('onLaunch');
		},
		onError() {
			alert('error');
		},

2) Obtener el esquema de URL en otros navegadores
| Documentación abierta de WeChat (qq.com)

					<u-button
						class="btn active"
						v-bind:class="{ Taa: isclass }"
						type="primary"
						size="medium"
						@tap="getscheme"
						v-else
					>
						进入房间
					</u-button>


---------------------------------------------------

		getscheme() {
			
			let _this=this;
			if(this.label_no!==''){
			uni.request({
				url: this.siteBaseUrl+'/appBaseUser/generatescheme',
				method: 'POST',
				data:{
					url:'pages/homepage/home',
					query:"label_no=" + this.label_no
				},
				success(res) {
					if(_this.label_no!==''){
					location.href = res.data.data.openlink;
					}
					
				}
			});}
		},

3. H5 comparte imágenes en WeChat

La aplicación se puede realizar y el h5 integrado de la aplicación también se puede realizar, pero el h5 independiente no se puede realizar

Si es una aplicación , use la API oficial proporcionada por uniapp: uni.share

(100 mensajes) h5 Haga clic en el botón para generar una imagen para compartir WeChat Moments_Haga clic en el botón en el backend para compartir Momentos Cómo obtenerlo_Tempered Program Yuan's Blog-CSDN Blog

H5 guarda imágenes localmente

Tampoco es factible que h5 guarde imágenes localmente en el navegador. 

Si es una aplicación , use la API oficial proporcionada por uniapp:

 Referencia de código específico: (100 mensajes) APLICACIÓN, H5 guardar imágenes en local

Guess you like

Origin blog.csdn.net/m0_65720832/article/details/130105902