php 微信分享可编辑分享标题、内容、图标

发布时间:2024年01月21日
微信分享

1、服务端
//生成签名的随机串
function nonceStr($length){
$str = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;//62个字符
s t r l e n = 62 ; w h i l e ( strlen = 62; while( strlen=62;while(length > $strlen){
$str .= $str;
$strlen += 62;
}
s t r = s t r s h u f f l e ( str = str_shuffle( str=strs?huffle(str);
return substr( s t r , 0 , str,0, str,0,length);
}

//获取access_token
public function access_token(){
    $app_id = $this->config['app_id'];
    $app_secret = $this->config['app_secret'];
    $result = $this->get_by_curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$app_id."&secret=".$app_secret);
    $json = json_decode($result,true);
    $access_token = $json['access_token'];
    return $access_token;
}

//获取ticket
public function get_ticket(){
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$this->access_token();
    $res = json_decode($this->get_by_curl( $url ));
    $ticket = $res->ticket;
    return $ticket;
}

/**
 * 请求微信接口获取数据
 * @param $url
 * @param bool $post
 * @return bool|string
 */
function get_by_curl($url,$post = false){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if($post){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

//分享获取config
function getWxConfig() {
    $appid = $this->config['app_id'];
    $jsapiTicket = $this->get_ticket();
    $url = '';
    $timestamp = time();
    $nonceStr = $this->nonceStr(16);
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    $signature = sha1 ( $string );

    $WxConfig["appId"] = $appid;
    $WxConfig["nonceStr"] = $nonceStr;
    $WxConfig["timestamp"] = $timestamp;
    $WxConfig["url"] = $url;
    $WxConfig["signature"] = $signature;
    $WxConfig["rawString"] = $string;
    return json_encode($WxConfig);
}

2、前端
<script>
function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    return (arr=document.cookie.match(reg))?unescape(arr[2]):null;
}

$(function() {
    //对url进行编码
    var localUrl = encodeURIComponent(location.href.split('#')[0]);
    //url传到后台格式
    var Url = "URL=" +localUrl;
    //这几个参数都是后台从微信公众平台获取到的
    var nonceStr, signature, timestamp, appId, shareUrl;
    $.ajax({
        //后台获取参数接口
        url: "/getWxConfig",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Token", getCookie("token"));
        },
        type: 'get',
        data: Url,
        success: function(data) {
            //得到参数
            var appId = JSON.parse(data).appId;
            var nonceStr = JSON.parse(data).nonceStr;
            var signature = JSON.parse(data).signature;
            var timestamp = JSON.parse(data).timestamp;
            var shareUrl = JSON.parse(data).url;
            //通过微信config接口注入配置
            wx.config({
                debug: false, // 默认为false  为true的时候是调试模式,会打印出日志
                appId: appId,
                timestamp: timestamp,
                nonceStr: nonceStr,
                signature: signature,
                jsApiList: [
                    'checkJsApi',
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo'
                ]
            });
            //配置自定义分享内容
            window.share_config = {
                'share': {
                    'imgUrl': '图标', // 这里是需要展示的图标
                    'desc': '描述', // 这是分享展示的摘要
                    'title': '标题', // 这是分享展示卡片的标题
                    'link': shareUrl, // 这里是分享的网址
                    'success': function(rr) {
                        //console.log('成功' + JSON.stringify(rr))
                    },
                    'cancel': function(tt) {
                        //console.log('失败' + JSON.stringify(tt));
                    }
                }
            };
            wx.ready(function() {
                wx.onMenuShareAppMessage(share_config.share); // 微信好友
                wx.onMenuShareTimeline(share_config.share); // 微信朋友圈
                wx.onMenuShareQQ(share_config.share); // QQ
            });

        },
        error: function(err) {

        },
    });

})
</script>
文章来源:https://blog.csdn.net/qq_16659821/article/details/135691456
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。