PHP implements WeChat SDK sharing interface
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
