微信开发之微信分享 + php
html
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>微信分享</title> <script type="text/javascript" src="/static/index/js/jquery.js"></script> <script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script> </head> <body> <script type="text/javascript" charset="utf-8"> wx.config({ debug: false, appId: '{$signPackage.appId}', timestamp: {$signPackage.timestamp}, nonceStr: '{$signPackage.nonceStr}', signature: '{$signPackage.signature}', jsApiList: [ // 所有要调用的 API 都要加到这个列表中 'updateAppMessageShareData', 'updateTimelineShareData' ] }); // 在这里调用 API wx.ready(function () { // 分享朋友及qq wx.updateAppMessageShareData({ title: '测试分享标题', // 分享标题 desc: '分享描述', // 分享描述 link: 'http://test.zizhuyou.site/index/Plantocr/index', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: 'http://test.zizhuyou.site/static/index/images/dog.png', // 分享图标 success: function () { // 设置成功 console.log('设置成功'); //alert('分享朋友或QQ成功'); }, }); // 分享朋友圈及QQ空间 wx.updateTimelineShareData({ title: '测试分享标题', // 分享标题 link: 'http://test.zizhuyou.site/index/Plantocr/index', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: 'http://test.zizhuyou.site/static/index/images/dog.png', // 分享图标 success: function () { // 设置成功 //alert('分享朋友圈及QQ空间成功'); } }) }) </script> </body> </html>
PHP
/** * 微信分享 */ public function share(){ $signPackage = json_decode($this->getSignPackage(),true); $this->assign('signPackage',$signPackage); return $this->fetch(); } /** * 生成签名 */ public function getSignPackage() { // 实例化微信操作类 $wx = new Wechat(); // 获取 ticket $jsapiTicket = $wx->getJsApiTicket(); // 注意 URL 一定要动态获取,不能 hardcode. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; // 当前页面的url $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); //生成签名的时间戳 $nonceStr = $this->createNonceStr(); //生成前面的随机串 // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; // 对string进行sha1加密 $signature = sha1($string); $signPackage = array( "appId" => $wx->APPID, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return json_encode($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; }