一、前序:之前遇到的问题,需要做一个海报微信分享的时候是一个卡片类型,里面有文字有图片有介绍

二、思路,把链接放入自己公众号,这样分享出去的就有这些了

三、使用

1、引入微信js

这个简单,不论uniapp还是普通html最外层都有一个html,我以uniapp为例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <script>
      var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
        CSS.supports('top: constant(a)'))
      document.write(
        '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
        (coverSupport ? ', viewport-fit=cover' : '') + '" />')
    </script>
    <title></title>
    <!-- 微信JS-SDK  这里这里只要这里 下方 -->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
     <script>  
            window.jWeixin=window.wx;  
            delete window.wx;  
        </script>  

    <!-- 微信JS-SDK  这里这里只要这里 上方 -->

  </head>
  <body>
    <div id="app"><!--app-html--></div>
    <script type="module" src="/main.js"></script>
  </body>
</html>

简单把,第一个是引入,第二个是该名称为jWeixin,因为我不改的话总是出现wx.config不存在,这个我是真不会了

2、使用

//分享
		// #ifdef H5

		async initJSSDK(vardata) {
			jweixin.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来
				appId: vardata.appId,
				timestamp: vardata.timestamp,
				nonceStr: vardata.nonceStr,
				signature: vardata.signature,
				jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareAppMessage'] // 必填,需要使用的JS接口列表
			});

			jweixin.ready(() => {
				// 配置分享到朋友
				jweixin.updateAppMessageShareData({
					title: '优惠券', // 分享标题
					desc: '小小优惠券大全', // 分享描述
					link: 'https://xxxxxxxxxxxxxxxx6/index', // 分享链接
					imgUrl: 'httxxxxxxxxxxxxxxxx6.jpeg', // 分享图标
					success: function () {
						// 设置成功后的回调
					}
				});

				jWeixin.updateTimelineShareData({
					title: this.shareConfig.title,
					link: this.shareConfig.link,
					imgUrl: this.shareConfig.imgUrl,
					success: shareData.success,
					cancel: shareData.cancel,
					fail: shareData.fail
				});

				// 配置分享到朋友圈
				jweixin.updateTimelineShareData({
					title: '优惠券', // 分享标题
					link: 'https://xxxxxxxxxxxxxxxx6/index', // 分享链接
					imgUrl: 'httpsxxxxxxxxxxxxxxxx6BSp.jpeg', // 分享图标
					success: function () {
						// 设置成功后的回调
					}
				});
			});
		},
		// #endif

很简单吧,至于使用this.initJSSDK(config)应该都会吧

三、后端

说一下后端吧,我们后端不鸟我,我自己写,反正php,

<?php

namespace app\api\controller;

use app\common\controller\Api;

header('Access-Control-Allow-Origin:*');//允许跨域
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header('Access-Control-Allow-Headers:x-requested-with,content-type,token');//浏览器页面ajax跨域请求会请求2次,第一次会发送OPTIONS预请求,不进行处理,直接exit返回,但因为下次发送真正的请求头部有带token,所以这里设置允许下次请求头带token否者下次请求无法成功
    exit("ok");
}

/**
 * 微信接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取微信公众号H5分享参数
     * @return \think\response\Json
     */
    public function getShareConfig()
    {
        // try {
            // 获取微信配置
           $config = get_addon_config('wechat');
            
            
            if (empty($config['app_id']) || empty($config['secret'])) {
                $this->error('微信配置不完整,请先配置微信插件');
            }

            // 获取当前页面URL(从前端传递或使用referer)
            $url = $this->request->param('url', '', 'trim');
            if (empty($url)) {
                $url = $this->request->server('HTTP_REFERER', '');
            }

            if (empty($url)) {
                $this->error('缺少页面URL参数');
            }

            // 生成随机字符串
            $nonceStr = $this->generateNonceStr();

            // 获取当前时间戳
            $timestamp = time();

            // 获取access_token
            $accessToken = $this->getAccessToken($config['app_id'], $config['secret']);

            // 获取jsapi_ticket
            $jsapiTicket = $this->getJsapiTicket($accessToken);

            // 生成签名
            $signature = $this->generateSignature($jsapiTicket, $nonceStr, $timestamp, $url);

            $result = [
                'appId' => $config['app_id'],
                'timestamp' => $timestamp,
                'nonceStr' => $nonceStr,
                'signature' => $signature
            ];
            
             $this->success('获取成功', $result);
            
        // } catch (\Exception $e) {
        //     // 记录详细错误信息用于调试
        //     \think\Log::error('微信分享配置获取失败:' . $e->getMessage());
        //     \think\Log::error('错误文件:' . $e->getFile() . ' 行号:' . $e->getLine());
        //     \think\Log::error('错误堆栈:' . $e->getTraceAsString());
            
        //     $this->error('获取失败:' . $e->getMessage());
        // }
    }

    /**
     * 生成随机字符串
     * @param int $length
     * @return string
     */
    private function generateNonceStr($length = 16)
    {
        $chars = 'abcBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取access_token
     * @param string $appId
     * @param string $appSecret
     * @return string
     */
    private function getAccessToken($appId, $appSecret)
    {
        // 缓存key
        $cacheKey = 'wechat_access_token_' . $appId;
        
        // 尝试从缓存获取
        $accessToken = cache($cacheKey);
        
        if (empty($accessToken)) {
            // 从微信API获取
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
            \think\Log::info('请求微信access_token,URL:' . $url);
            
            $response = file_get_contents($url);
            if ($response === false) {
                throw new \Exception('无法连接到微信服务器获取access_token');
            }
            
            \think\Log::info('微信access_token响应:' . $response);
            $data = json_decode($response, true);
            
            if (isset($data['access_token'])) {
                $accessToken = $data['access_token'];
                // 缓存access_token,有效期7200秒,提前5分钟过期
                cache($cacheKey, $accessToken, 6900);
            } else {
                throw new \Exception('获取access_token失败:' . ($data['errmsg'] ?? '未知错误') . ',错误码:' . ($data['errcode'] ?? '无'));
            }
        }
        
        return $accessToken;
    }

    /**
     * 获取jsapi_ticket
     * @param string $accessToken
     * @return string
     */
    private function getJsapiTicket($accessToken)
    {
        // 缓存key
        $cacheKey = 'wechat_jsapi_ticket_' . md5($accessToken);
        
        // 尝试从缓存获取
        $jsapiTicket = cache($cacheKey);
        
        if (empty($jsapiTicket)) {
            // 从微信API获取
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi";
            $response = file_get_contents($url);
            $data = json_decode($response, true);
            
            if (isset($data['ticket']) && $data['errcode'] == 0) {
                $jsapiTicket = $data['ticket'];
                // 缓存jsapi_ticket,有效期7200秒,提前5分钟过期
                cache($cacheKey, $jsapiTicket, 6900);
            } else {
                throw new \Exception('获取jsapi_ticket失败:' . ($data['errmsg'] ?? '未知错误'));
            }
        }
        
        return $jsapiTicket;
    }

    /**
     * 生成签名
     * @param string $jsapiTicket
     * @param string $nonceStr
     * @param int $timestamp
     * @param string $url
     * @return string
     */
    private function generateSignature($jsapiTicket, $nonceStr, $timestamp, $url)
    {
        // 去除URL中的fragment部分(#后面的内容)
        $url = strtok($url, '#');
        
        // 按字典序排序参数
        $params = [
            'jsapi_ticket' => $jsapiTicket,
            'noncestr' => $nonceStr,
            'timestamp' => $timestamp,
            'url' => $url
        ];
        
        // 拼接字符串
        $string = '';
        foreach ($params as $key => $value) {
            $string .= $key . '=' . $value . '&';
        }
        $string = rtrim($string, '&');
        
        // 生成签名
        return sha1($string);
    }
}

问我啥意思就别问了,我也不清楚,反正能用

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐