-
-
Save edk24/7597c2652f2805aac93d6cad48b33656 to your computer and use it in GitHub Desktop.
微信公众号开发 - 分享卡片代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace library\wechat; | |
use RuntimeException; | |
use think\facade\Cache; | |
/** | |
* 微信公众平台签名 | |
* 我个人喜欢把这类文件放到tp的 extends/library 下,你可以根据你的喜好自己放, 记得修改命名空间 | |
*/ | |
class Sign | |
{ | |
protected $appid; | |
protected $appsecret; | |
public function __construct(string $appid, string $appsecret) | |
{ | |
$this->appid = $appid; | |
$this->appsecret = $appsecret; | |
} | |
/** | |
* 生成随机字符串 | |
* | |
* @param integer $length | |
* @return string | |
*/ | |
public static function generateNonceStr(int $length = 16): string | |
{ | |
// 密码字符集,可任意添加你需要的字符 | |
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | |
$str = ""; | |
for ($i = 0; $i < $length; $i++) { | |
$str .= $chars[mt_rand(0, strlen($chars) - 1)]; | |
} | |
return $str; | |
} | |
/** | |
* 签名 | |
* | |
* @param string $signUrl 签名地址, 留空则是 $_SERVER['HTTP_REFERER'] | |
* @return array | |
*/ | |
public function signtrue(string $signUrl = ''): array | |
{ | |
// 检查地址 | |
if (strstr($signUrl, '#')) { | |
throw new RuntimeException('签名失败,链接中不能包含 #!'); | |
} | |
$ticket = $this->getTicket(); | |
$timestamp = (string)time(); | |
$noncestr = self::generateNonceStr(); | |
$str = sprintf('jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s', $ticket, $noncestr, $timestamp, $signUrl); | |
$signature = sha1($str); | |
$data = [ | |
'appid' => $this->appid, | |
'timestamp' => $timestamp, | |
'noncestr' => $noncestr, | |
'signature' => $signature, | |
'link' => $signUrl | |
]; | |
return $data; | |
} | |
/** | |
* 获取微信公众平台 Ticket | |
* | |
* @return string | |
*/ | |
protected function getTicket(): string | |
{ | |
$ticket = Cache::get('ticket'); | |
if ($ticket) { | |
return $ticket; | |
} | |
$url = sprintf('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi', $this->getAccessToken()); | |
$response = file_get_contents($url); | |
$result = json_decode($response, true); | |
if (!isset($result['ticket'])) { | |
throw new RuntimeException('获取 ticket 失败, ' . $response); | |
} | |
$ticket = $result['ticket']; | |
Cache::set('ticket', $ticket, 7200); | |
return $ticket; | |
} | |
/** | |
* 获取微信公众平台 AccessToken | |
* | |
* @return string | |
*/ | |
protected function getAccessToken():string | |
{ | |
$access_token = Cache::get('access_token'); | |
if ($access_token) { | |
return $access_token; | |
} | |
$url = sprintf('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s', $this->appid, $this->appsecret); | |
$response = file_get_contents($url); | |
$result = json_decode($response, true); | |
if (!isset($result['access_token'])) { | |
throw new RuntimeException('获取 access_token 失败, ' . $response); | |
} | |
$access_token = $result['access_token']; | |
Cache::set('access_token', $access_token, 7200); | |
return $access_token; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { onLaunch } from '@dcloudio/uni-app'; | |
import { sign } from './api/activity'; // 签名接口 | |
import wx from 'weixin-js-sdk' // 此处需要安装 jssdk 包: npm install weixin-js-sdk -S | |
// 此处用 uniapp vue3举例 | |
// 获取签名后 调用 wx.config 配置, 然后配置分享信息就可以了 | |
// 官方文档参考地址: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#4 | |
onLaunch(() => { | |
// 签名 | |
sign() | |
.then((data) => { | |
const { appid, timestamp, noncestr, signature } = data | |
wx.config({ | |
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 | |
appId: appid, // 必填,公众号的唯一标识 | |
timestamp:timestamp, // 必填,生成签名的时间戳 | |
nonceStr: noncestr, // 必填,生成签名的随机串 | |
signature: signature,// 必填,签名 | |
jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填,需要使用的JS接口列表 | |
}); | |
wx.ready(function () { //需在用户可能点击分享按钮前就先调用 | |
wx.updateAppMessageShareData({ | |
title: data.title, // 分享标题 | |
desc: data.desc, // 分享描述 | |
link: data.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 | |
imgUrl: data.imgUrl, // 分享图标 | |
success: function () { | |
// 设置成功 | |
} | |
}) | |
wx.updateTimelineShareData({ | |
title: data.title, // 分享标题 | |
link: data.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 | |
imgUrl: data.imgUrl, // 分享图标 | |
success: function () { | |
// 设置成功 | |
} | |
}) | |
}); | |
}) | |
}) | |
// ⚠️: 关于 jssdk 包, 如果你是原生开发, 可以直接在head引入 <script type="text/javascript" src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script> | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
特别需要注意的一点⚠️ ⚠️ :
从链接点进去的分享是不会变成卡片的,需要把链接做成二维码扫描进去分享才会显示成卡片样式