search
HomeWeb Front-endH5 TutorialWeChat development practical sharing function

WeChat development practical sharing function

Jun 20, 2017 pm 01:57 PM
Actual combatplatformdevelopWeb page

By understanding the requirements, it can be broken down into:

(1) WeChat mobile phone users can use WeChat’s JSSDK.

(2) Select the image and use "chooseImage" of JSSDK. Since the local address cannot be shared when sharing the image, "uploadImage" of JSSDK is also needed.

(3) Sharing to Moments requires "onMenuShareTimeline" of JSSDK.

Taken together, the business logic is shown in Figure 4.5.

Figure 4.5 Business logic structure diagram

First copy the JSSDK environment to the directory of this section and create an index. html file, imageSharing.js file, the directory structure is shown in Figure 4.6.

Figure 4.6 Section 4.2 Directory Structure

Modify the configuration file of the JSSDK environment, the code is as follows:

01	jsApiList: [ // 必填,需要使用的JS接口列表,所有JS接口列表见附录B
02	    "chooseImage",
03	    "previewImage",
04	    "uploadImage",
05	    "onMenuShareTimeline"
06	]
07	//其他代码略

Build a The click button with "id" equal to "chooseImage", and the container used to display the selected image after clicking the button, add the following code to the index.html file:

01	<!DOCTYPE html>
02	<html lang="en">
03	<head>
04		<meta charset="UTF-8">
05	    <meta name="viewport" content="width=device-width, initial-scale=1.0, 
06	minimum-scale=1, maximum-scale=1.0, user-scalable=no">
07	    <title>第4章 4.2节-实例:从手机相册中选照片然后分享</title>
08	    <!--依赖文件:jQuery-->
09	    <script src="./js/jquery-1.11.2.min.js?1.1.10"></script>
10	    <!--依赖文件:微信的JSSDK源文件-->
11	    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js?1.1.10"></script>
12	    <!--依赖文件:coolie-->
13	    <script src="./js/cookie.js?1.1.10"></script>
14	    <!--JSSDK的环境-->
15	    <script src="./js/wxJSSDK.js?1.1.10"></script>
16	    <!--引入检测API的图像服务-->
17	    <script src="imageSharing.js?1.1.10"></script>
18	    <style>
19	        input{
20	            width: 100%;
21	            padding: 0.2em;
22	            background-color: #5eb95e;
23	            font-size: 1.4em;
24	            background-image: linear-gradient(to bottom, #62c462, #57a957);
25	            background-repeat: repeat-x;
26	            color: #ffffff;
27	            text-align: center;
28	            text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
29	            border-radius: 0.3em;
30	        }
31	    </style>
32	</head>
33	<body>
34	    <h1 id="">:)</h1>
35	    <b style="font-size: 2em">实例:从手机相册中选照片然后分享,支持选择1张图片!
36	</b><br /><br />
37	    <p id="imageContainer" style="text-align: center;width: 100%"></p>
38	    <p id="selectImg" style="color: #5eb95e;text-align: center">没有自定义分享图片</p>
39	    <input type="button" value="请选择分享图片" id="chooseImage" /><br /><br />
40	</body>
41	</html>

Add processing business to the imageSharing.js file The code is as follows:

01	/*
02	 函数名称:wxJSSDK.shareApi
03	 函数功能:为wxJSSDK增加分享模块
04	 参数:
05	 shareList(Array) 必选项,待分享的API配置表
06	 */
07	wxJSSDK.shareApi = function(shareList){
08	    if(wxJSSDK.isReady){//wxJSSDK.isReady 查看微信JSSDK是否初始化完毕
09	
10	        //获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
11	        if(shareList.onMenuShareTimeline){
12	            var ParametersTimeline = shareList.onMenuShareTimeline;
13	            wx.onMenuShareTimeline({
14	                title: ParametersTimeline.title, 		// 分享标题
15	                link: ParametersTimeline.link,		// 分享链接
16	                imgUrl: ParametersTimeline.imgUrl, 	// 分享图标
17	                success: function () {
18	                    // 用户确认分享后执行的回调函数
19	                    ParametersTimeline.success && ParametersTimeline.success();
20	                },
21	                cancel: function () {
22	                    // 用户取消分享后执行的回调函数
23	                    ParametersTimeline.cancel && ParametersTimeline.cancel();
24	                }
25	            });
26	        }
27	
28	    }else{
29	        console.log("抱歉,wx没有初始化完毕,请等待wx初始化完毕,再调用分享服务。");
30	    }
31	}
32	/*
33	 函数名称:wxJSSDK.imageApi
34	 函数功能:为wxJSSDK增加图像服务
35	 参数:
36	 imageApi 图像API Object 配置
37	 */
38	wxJSSDK.imageApi = function(imageApi){
39	    if(wxJSSDK.isReady){//wxJSSDK.isReady 查看微信JSSDK是否初始化完毕
40	        if(imageApi){
41	
42	            imageApi.chooseImage && wx.chooseImage({//拍照或从手机相册中选图接口
43	                success: function (res) {
44	                    imageApi.chooseImage.success && 
45	imageApi.chooseImage.success(res);
46	                }
47	            });
48	
49	            imageApi.previewImage && wx.previewImage({	// 预览图片接口
50	                current: imageApi.previewImage.current, 	// 当前显示的图片链接
51	                urls: imageApi.previewImage.urls 			// 需要预览的图片链接列表
52	            });
53	
54	            imageApi.uploadImage && wx.uploadImage({	// 上传图片接口
55	                localId: imageApi.uploadImage.localId, 		// 需要上传的图片的本地ID,
56	由chooseImage接口获得
57	                isShowProgressTips: imageApi.uploadImage.isShowProgressTips || 1, // 
58	默认为1,显示进度提示
59	                success: function (res) {
60	                    imageApi.uploadImage.success && 
61	imageApi.uploadImage.success(res);
62	                }
63	            });
64	
65	            imageApi.downloadImage && wx.downloadImage({//下载图片接口
66	                serverId:imageApi.downloadImage.serverId, // 需要下载的图片的服务器端
67	ID,由uploadImage接口获得
68	                isShowProgressTips: imageApi.downloadImage.isShowProgressTips || 1, // 
69	默认为1,显示进度提示
70	                success: function (res) {
71	                    imageApi.downloadImage.success && 
72	imageApi.downloadImage.success(res);
73	                }
74	            });
75	        }else{
76	            console.log("缺少配置参数");
77	        }
78	    }else{
79	        console.log("抱歉,wx没有初始化完毕,请等待wx初始化完毕,再调用图像接口服
80	务。");
81	    }
82	
83	}
84	
85	window.onload = function(){
86	    var chooseImageID,	// 拍照或从手机相册中选图接口
87	        shareImage,
88	        uploadImage = function(back){
89	            wxJSSDK.imageApi({	// 上传图片···
90	                uploadImage:{
91	                    localId:chooseImageID.toString(),
92	                    success:function(res){//临时access_token,上传图片成功之后,执行分
93	享操作
94	                   shareImage = 
95	"http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=
96	eQv3HPwEFxwsw8cyh5O7DjaNOoGd4d-jYtG_c9uW-YbwUYxkMywh_O3LCC
97	ZtmX8ZWr8np0Q5CqAox7lghNkNuiNHU8M618jbRvcaLjQuHq8&media_id="+res.serverId; // 返回图片的服务器端ID
98	                        back && back();
99	                    }
100	                }
101	            });
102	        },
103	        shareTimeline = function(){
104	            uploadImage(function(){
105	                wxJSSDK.shareApi({					// 分享图片···
106	                    onMenuShareTimeline : {			// 分享到朋友圈
107	                        title: "实例:从手机相册中选照片然后分享!", // 分享标题
108	                        link: &#39;http://weibo.com/xixinliang&#39;, 	// 分享链接
109	                        imgUrl: shareImage, 			// 分享图标
110	                        success: function () {
111	
112	                        },
113	                        cancel: function () {
114	
115	                        }
116	                    }
117	                });
118	            });
119	        };
120	    $("#chooseImage").click(function(){
121	        wxJSSDK.imageApi({
22	            chooseImage:{
23	                success:function(res){
24	                    chooseImageID =  res.localIds[0]; // 返回选定照片的本地ID列表,
25	localId可以作为img标签的src属性显示图片
26	                    $("#imageContainer").html("<img src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/article/000/000/001/17c991ba38dceb9bfbf33b6cf0582a8e-2.png?x-oss-process=image/resize,p_40"  class="lazy"  style=&#39;width: 30%&#39; 
27	src=&#39;"+chooseImageID+"&#39;>");
28	                    $("#selectImg").html("已选择图片,请点击右上角分享到朋友圈按钮");
29	                    shareTimeline();
30	                }
31	            }
32	        });
33	    });
34	}

[Code explanation]

  • In index.html, a button to share a custom image is created, such as As shown in Figure 4.7.

  • Click the share button and call the JSSDK’s image selection API to allow the user to select the image, as shown in Figure 4.8.

Figure 4.7 Custom Sharing Picture UI

Figure 4.8 After selecting the UI

  • , call "uploadImage" to upload the image.

  • After the upload is successful, return the server "serverId" after uploading, then call the multimedia download API, and assign the image to the JSSDK sharing API "onMenuShareTimeline".

Users can view the sharing effect, as shown in Figure 4.9 and Figure 4.10.

Figure 4.9 Sharing to Moments Editing UI

Figure 4.10 Successfully Sharing Custom Pictures to Moments

The above is the detailed content of WeChat development practical sharing function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

How to do h5 linkHow to do h5 linkApr 06, 2025 pm 12:39 PM

How to create an H5 link? Determine the link target: Get the URL of the H5 page or application. Create HTML anchors: Use the <a> tag to create an anchor and specify the link target URL. Set link properties (optional): Set target, title, and onclick properties as needed. Add to webpage: Add HTML anchor code to the webpage where you want the link to appear.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.