微信h5分享好友和朋友圈

微信自定义分享好友或朋友圈,js代码记录

1、普通微信公众号wxShare.js




window['wx'] = wx;
const shareConfig = {
    messageTitle: "2023-2024腾讯视频大剧片单",
    desc: "拥抱多元、尊重艺术、追求精品",
    timelineTitle: "2023-2024腾讯视频大剧片单",
    urlLink: "https://cdn.mxxx.cn/wei/tengxunPos",
    imgUrl: "https://cdn.mxxx.cn/wei/tengxunPos/imgs/share.jpg",
};


window.ShareAppMessage = { // 好友
	title: shareConfig.messageTitle,
	desc: shareConfig.desc,
	link: shareConfig.urlLink,
	imgUrl: shareConfig.imgUrl,
	success: () => {
		if (_hmt) _hmt.push(['_trackEvent', 'shareConfig', 'share', '分享好友']);
	},
	cancel: () => {

	}
}
window.ShareTimeline = { // 朋友圈
	title: shareConfig.timelineTitle,
	link: shareConfig.urlLink,
	imgUrl: shareConfig.imgUrl,
	success: () => {
		if (_hmt) _hmt.push(['_trackEvent', 'shareConfig', 'share', '分享朋友圈']);
	},
	cancel: () => {

	}
}
//替换为腾讯的接口
$.ajax({
	type: "POST",
	url: 'http://hi.mxxx.cn/api/jssdk.php', //获取appid以及签名的接口
	dataType: "json",
	data: { url: window.location.href },
	success: function (res) {
		// 返回值 res.status
		var data = res;
		wx.config({
			debug: false,
			appId: data.appid,
			timestamp: data.timestamp,
			nonceStr: data.noncestr,
			signature: data.signature,
			jsApiList: [
				'onMenuShareTimeline',
				'onMenuShareAppMessage',
				'hideMenuItems',
				'chooseImage',
				'uploadImage',
				'scanQRCode',
				'startRecord', //开始录音
				'stopRecord', //停止录音
				'onVoiceRecordEnd', //监听录音自动停止接口录音时间超过一分钟没有停止的时候会执行 complete 回调
				'playVoice', //播放语音接口
				'pauseVoice', //暂停播放接口
				'stopVoice', //停止播放接口
				'onVoicePlayEnd', //监听语音播放完毕接口
				'uploadVoice', //上传语音接口
				"scanQRCode", //扫一扫
			],
			openTagList: [
				'wx-open-launch-weapp', //跳转小程序
				'wx-open-launch-app', //跳转app
				'wx-open-subscribe' //订阅消息
			]
		});
		wx.ready(() => {
			wx.onMenuShareAppMessage(window.ShareAppMessage); //好友
			wx.onMenuShareTimeline(window.ShareTimeline); //朋友圈
			wx.hideMenuItems({
				menuList: [
					'menuItem:share:qq',
					'menuItem:share:weiboApp',
					'menuItem:favorite',
					'menuItem:share:facebook',
					'menuItem:copyUrl',
					'menuItem:readMode',
					'menuItem:openWithQQBrowser',
					'menuItem:openWithSafari'
				]
			});
		});
		wx.error((res) => {
			console.log(res)
		})
	},
});

2、jssdk.php 接口

<?php
include 'WechatJssdk.class.php';


header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');


//$datas=file_get_contents("php://input");

$appid = 'wxxxxxxxxxxxxxx03f';
$secret = '63xxxxxxxxxxxxxxxbe637';

$url =isset($_POST['url']) ? $_POST['url'] : '';
//$url=urldecode($url);

$jssdk = new WechatJssdk($appid,$secret,$url);
$sign = $jssdk->GetSignPackage();
$data['appid'] = $sign['appId'];
//$data['aa'] = $_POST['url'];
//$data['bb'] = $datas;
$data['noncestr'] = $sign['nonceStr'];
$data['signature'] = $sign['signature'];
$data['timestamp'] = $sign['timestamp'];
$data['url'] = $sign['url'];
//$data['jsapi_ticket'] = $sign['jsapi_ticket'];

$getAccessToken =$_GET["Token"];
if($getAccessToken=="Token"){
 echo json_encode($sign["accessToken"]);
}else{
    echo json_encode($data);
}

3、jssdk.php 同目录下的 WechatJssdk.class.php

<?php

class WechatJssdk
{
    private $appId;
    private $appSecret;
    private $appUrl;

    public function __construct($appId, $appSecret, $appUrl = '')
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $this->appUrl = $appUrl;
    }

    public function getSignPackage()
    {
        $jsapi = $this->getJsApiTicket();
        if (!$this->appUrl) {
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        } else {
            $url = $this->appUrl;
        }
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $jsapiTicket = $jsapi["ticket"];
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string,
            // 'jsapi_ticket' => $jsapiTicket,
            // 'accessToken' => $jsapi["accessToken"]
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket()
    {
        // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("jsapi_ticket.json"));
        $accessToken = $this->getAccessToken();
        $ticket["accessToken"] = $accessToken;
        if ($data->expire_time < time()) {
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket["ticket"] = $res->ticket;
            if ($ticket["ticket"]) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket["ticket"];
                $fp = fopen("jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket["ticket"] = $data->jsapi_ticket;
        }

        return $ticket;
    }

    private function getAccessToken()
    {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("access_token.json"));
        if ($data->expire_time < time()) {
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen("access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}


以下再贴一个放腾讯域名下的分享配置,自家的就是方便简单,这是腾讯老客户端遗留下来的一个接口,直接在html调用就可以了:

document.addEventListener("WeixinJSBridgeReady",function(){
    weixinJSBgReadyEventSet();
}) ;

function weixinJSBgReadyEventSet(){
    var appid=  "wxca942bbff22e0e51";//经常设置为'' 'wx5730acbd9e2bc03f' 小意思
    var title = "2023-2024腾讯视频大剧片单";
    var link = "https://m.v.qq.com/2023piandan/index.html";  
    var desc = "拥抱多元、尊重艺术、追求精品";
    var img_url = "https://m.v.qq.com/2023piandan/imgs/share.jpg";
    var img_width = "120";//好像设置成其他也没用
    var img_height = "120";
    share(appid,title,link,desc,img_url,img_width,img_height,'menu:share:timeline','shareTimeline');//timeline:分享至朋友圈
    share(appid,title,link,desc,img_url,img_width,img_height,'menu:share:appmessage','sendAppMessage');//appmessage分享至微信好友
}

function share(appid,title,link,desc,img_url,img_width,img_height,button,event) {
    if (typeof WeixinJSBridge == "undefined") {
        alert("请先通过微信分享文章 ");
    } else if (typeof window.WeixinJSBridge.invoke == 'undefined'){
        alert("invoke!");
    }
    else {
        WeixinJSBridge.on(button, function(argv){
            WeixinJSBridge.invoke(event,{
                "appid":appid,             //设置为null
                "title": title,
                "link": link,
                "desc": desc,
                "img_url": img_url,
                "img_width":img_width,                            //图片宽度
                "img_height":img_height                            //图片高度
            }, function(d) {
                //alert(d.err_msg);//这里是分享功能的回调函数,有错误的时候有用
            });
        });
    }
}

放在最后提醒,html页面记得引入三个文件
 

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script type="text/javascript" src="js/wxShare.js?v=4.2"></script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dove言和

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值