微信分享自定義鏈接給朋友

//php
    public function index(){
        $time = time();
        $nonceStr = self::createNonceStr();// 祕鑰
        $res = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}");// 獲得token
        $ress = json_decode($res,True);
        $token = $ress['access_token'];// 取出  
        $js = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token."&type=jsapi");
        $jss = json_decode($js,True);
        $jsapi_ticket = $jss['ticket'];//   取出JS憑證

        $dataa['noncestr'] =  $nonceStr; //隨意字符串 傳到JS裏去要一致
        $dataa['jsapi_ticket'] = $jsapi_ticket;
        $dataa['timestamp'] = $time;
        $dataa['url'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];//動態獲取URL
        ksort($dataa);
        $signature = '';
        foreach($dataa as $k => $v){
            $signature .= $k.'='.$v.'&';
        }
        $dataa['signature'] = sha1(substr($signature, 0, strlen($signature)-1));// 必填,簽名
        $dataa['appid'] = $appid;
}


    public static 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;
    }


//js
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
    wx.config({
        debug:true,
        appId: '{$dataa["appid"]}',
        timestamp: '{$dataa["timestamp"]}',
        nonceStr: '{$dataa["noncestr"]}',
        signature: '{$dataa["signature"]}',
        jsApiList: [
            'onMenuShareAppMessage'
        ]
    });

    wx.ready(function(){
//        通過checkJsApi判斷當前客戶端版本是否支持分享參數自定義
        wx.checkJsApi({
            jsApiList: [
                'onMenuShareAppMessage'
            ],
            success: function (res) {
//                alert(JSON.stringify(res));
            }
        });
        wx.onMenuShareAppMessage({
            title: '標題', // 分享標題
            desc: '描述', // 分享描述
            link: '{$dataa["url"]}', // 分享鏈接
            imgUrl: '/2018/6/16zJCYcCloJ.png', // 分享圖標
            success: function () {
                alert('分享成功');
            },
            cancel: function () {
                alert('取消分享了');
            }
        });
    });
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章