123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
-
- import request from "./request"
-
- const jsApiList = [
- 'updateAppMessageShareData',
- 'updateTimelineShareData',
- 'onMenuShareTimeline',
- 'onMenuShareAppMessage',
- 'onMenuShareQQ',
- 'onMenuShareWeibo',
- 'onMenuShareQZone'
- ]
-
- function initSDK (url) {
- request(`https://api.h5.njyunzhi.com/mp/jssdk?url=${encodeURIComponent(url)}`).then((res) => {
- window.wx.config({
- debug: process.env.NODE_ENV === 'development', // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
- appId: res.appId, // 必填,公众号的唯一标识
- timestamp: res.timestamp, // 必填,生成签名的时间戳
- nonceStr: res.nonceStr, // 必填,生成签名的随机串
- signature: res.signature, // 必填,签名
- jsApiList // 必填,需要使用的JS接口列表
- })
- })
- }
-
- /**
- * 分享
- * @param {*} opt
- */
- export function share (opt) {
- const { origin, pathname } = window.location
- const defaultLink = origin + pathname
- const defaultImg = `${origin}${pathname}images/share.jpg`
-
- const link = window.location.href // opt.link || defaultLink
- const imgUrl = opt.imgUrl || defaultImg
-
- initSDK(link)
- window.wx.ready(function () {
- jsApiList.map((apiName) => {
- const api = window.wx[apiName]
- api({
- title: opt.title || '', // 分享标题
- link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
- imgUrl, // 分享图标
- desc: opt.desc || ''
- })
- })
- })
- }
-
- /**
- * 获取 code
- * @returns
- */
- function getCode () {
- const matched = /[?&]*code=([^&]+)/.exec(location.search)
- if (matched) {
- return decodeURIComponent(matched[1])
- }
- }
-
- /**
- * 跳转授权页面
- */
- export function redirect (force) {
- if (process.env.NODE_ENV === 'development') return;
-
- const originCode = localStorage.getItem('wxcode');
- const queryCode = getCode();
- localStorage.setItem('wxcode', queryCode)
-
- if (!queryCode || queryCode === originCode || force) {
- const local = encodeURIComponent(location.origin + location.pathname)
- const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd3bab568bc42d1de&redirect_uri=${local}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
- window.location.href = url
- }
- }
-
- /**
- * 获取 openid
- * @returns
- */
- export function getOpenId () {
- if (process.env.NODE_ENV === 'development') return Promise.resolve('123');
-
- const code = getCode()
- if (!code) {
- return Promise.reject("获取用户信息失败, 请刷新重试")
- }
-
- return request(`https://api.h5.njyunzhi.com/mp/openid?code=${encodeURIComponent(code)}`)
- }
-
- /**
- * 获取 openid
- * @returns
- */
- export function getUserInfo () {
- if (process.env.NODE_ENV === 'development') return Promise.resolve({ openid: '123' });
-
- const code = getCode()
- if (!code) {
- return Promise.reject("获取用户信息失败, 请刷新重试")
- }
-
- return request(`https://api.h5.njyunzhi.com/mp/userinfo?code=${encodeURIComponent(code)}`)
- }
|