Software development kit (foreign language abbreviation: SDK, foreign language full name: Software Development Kit) is generally a development tool used by some software engineers to create application software for specific software packages, software frameworks, hardware platforms, operating systems, etc. collection. This article mainly shares with you how to implement the WeChat SDK sharing interface in PHP. I hope it can help you.
<?php class Wxsdk { private $appId; private $appSecret; /* * 这里为威狮码的公众号的openid和appsecret,如果配置到其他的子商家会出现需要关注威狮码公众号, * 则需要获取数据库的vender表里面的openid和appsecret * */ public function __construct($appId = '自己的appid', $appSecret = '自己的appSecret') { $this->appId = $appId; $this->appSecret = $appSecret; } public function getSignPackage(Request $request) { //接收到前端的转义url转义回来 $url = $_POST; $durl = $url['url']; $durl = urldecode($durl); $jsapiTicket = $this->getJsApiTicket(); $timestamp = time(); $nonceStr = $this->createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$durl"; $signature = sha1($string); $signPackage = [ "appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ]; // var_dump($signPackage);die; throw new SuccessMessage(['msg' => $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("jssdk/jsapi_ticket.json")); if ($data->expire_time < time()) { $accessToken = $this->getAccessToken(); //定义传递的参数数组 $params['type'] = 'jsapi'; $params['access_token'] = $accessToken; $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $params['access_token'] . "&type=" . $params['type'] . ""; $res = json_decode(curl_get($url, $params)); $ticket = isset($res->ticket) ? $res->ticket : NULL; if ($ticket) { $res->expire_time = time() + 7000; $res->jsapi_ticket = $ticket; $fp = fopen("jssdk/jsapi_ticket.json", "w"); fwrite($fp, json_encode($res)); fclose($fp); } } else { $ticket = $data->jsapi_ticket; } return $ticket; } private function getAccessToken() { // access_token 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode(file_get_contents("jssdk/access_token.json")); if ($data->expire_time < time()) { //定义传递的参数数组 $params['grant_type'] = 'client_credential'; $params['appid'] = $this->appId; $params['secret'] = $this->appSecret; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" . $params['grant_type'] . "&appid=" . $params['appid'] . "&secret=" . $params['secret'] . ""; $res = json_decode(curl_post($url, $params)); $access_token = isset($res->access_token) ? $res->access_token : NULL; if ($access_token) { $res->expire_time = time() + 7000; $res->access_token = $access_token; $fp = fopen("jssdk/access_token.json", "w"); fwrite($fp, json_encode($res)); fclose($fp); } } else { $access_token = $data->access_token; } return $access_token; } 前端代码
Check the official steps and confirm the signature algorithm.
Confirm that the signature algorithm is correct, you can use the http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign page tool for verification.
Confirm that the nonceStr (standard capital S in camel case in js) and timestamp in the config are consistent with the corresponding noncestr and timestamp used in the signature.
Confirm that the url is the complete url of the page (please confirm on the current page alert(location.href.split('#')[0]), including 'http(s): //' part, and '? 'The GET parameter part after ', but does not include the part after '#'hash.
Confirm that the appid in config is consistent with the appid used to obtain jsapi_ticket.
Make sure to cache access_token and jsapi_ticket.
Make sure that the URL you obtain for signing is obtained dynamically. For dynamic pages, please refer to the PHP implementation in the example code. If it is a static page of html, the url is passed to the backend for signature through ajax on the front end. The front end needs to use js to get the link of the current page except the '#' hash part (can be obtained by location.href.split('#')[0], and need encodeURIComponent, background decodeURIComponent decoding), because once the page is shared, the WeChat client will add other parameters at the end of your link. If the current link is not obtained dynamically, the signature of the shared page will fail.
The signature is correct. If the above steps cannot solve your problem (invalid signature), then use the URL problem. Note: the WeChat official account must be configured with your debugging security Domain name (you can configure the second-level domain name: xxx.com instead of configuring multiple a.xxx.com/b.xxx.com, etc.).
Reason: WeChat will add multiple parameters to your current page when sharing. When you sha1, you must ensure that the url address is the address after WeChat adds parameters to you, so that config: invalid signature will not be reported.
Solution: The URL before sha1 must be a normal URL that can be directly recognized by the naked eye after decoding. If you are using a static page, before you configure wx.config, first pass encodeURIComponent(location.href.split ('#')[0]) passes the current url encoding to the background, and the background decodes it through decodeURIComponent. The core code is as follows:
Foreground html page, encoding the url:
jQuery.post("/xxx", {"url": encodeURIComponent(window.location.href.split('#')[0]),"t": new Date().getTime()}, function (result) { if (result.errno != 0) { alert("您当前的网络不稳定请稍后再试!"); return; } var shareUrl = result.data.url; wx.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: 'xxx', // 必填,公众号的唯一标识 timestamp: result.data.timestamp, // 必填,生成签名的时间戳 nonceStr: result.data.nonceStr, // 必填,生成签名的随机串 signature: result.data.signature,// 必填,签名,见附录1 jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 });
The above is the detailed content of PHP implements WeChat SDK sharing interface. For more information, please follow other related articles on the PHP Chinese website!