1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | <?php //获取微信access_token function getaccess_token(){ //appid与appsecret改成你自己的 $appid = '自己的appid' ; $appsecret = '自己的appsecret' ; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}" ; $ch = curl_init(); curl_setopt( $ch , CURLOPT_URL, $url ); curl_setopt( $ch , CURLOPT_RETURNTRANSFER,1); curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER,0); $data = curl_exec( $ch ); curl_close( $ch ); $data = json_decode( $data ,true); return $data [ 'access_token' ]; } //获取jsapi_ticket function getjsapi_ticket(){ $access_token = getaccess_token(); $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$access_token}" ; $ch = curl_init(); curl_setopt( $ch , CURLOPT_URL, $url ); curl_setopt( $ch , CURLOPT_RETURNTRANSFER,1); curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER,0); $data = curl_exec( $ch ); curl_close( $ch ); $data = json_decode( $data ,true); return $data [ 'ticket' ]; } //默认生成16位随机数 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 ; } //获取要排序的signature相关代码 function getSignPackage() { $jsapiTicket = getjsapi_ticket(); $protocol = (! empty ( $_SERVER [ 'HTTPS' ]) && $_SERVER [ 'HTTPS' ] !== 'off' || $_SERVER [ 'SERVER_PORT' ] == 443) ? "https://" : "http://" ; $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" ; $timestamp = time(); $nonceStr = createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url" ; $signature = sha1( $string ); $signPackage = array ( "appId" => '自己的appid' , "nonceStr" => $nonceStr , "timestamp" => $timestamp , "url" => $url , "signature" => $signature ); return $signPackage ; } $signPackage = getSignPackage(); ?> <!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" > <title>微信自定义分享</title> </head> <body> </body> <script> wx.config({ debug: true, appId: '<?php echo $signPackage["appId"];?>' , timestamp: <?php echo $signPackage [ "timestamp" ];?>, nonceStr: '<?php echo $signPackage["nonceStr"];?>' , signature: '<?php echo $signPackage["signature"];?>' , jsApiList: [ // 所有要调用的 API 都要加到这个列表中 'onMenuShareTimeline' , 'chooseImage' ] }); wx.ready( function () { wx.onMenuShareTimeline({ title: '王文晓博客' , success: function (res) { alert( '已分享' ); }, cancel: function (res) { alert( '已取消' ); }, fail: function (res) { alert(JSON.stringify(res)); } }) }); </script> </html> |
联系客服