wechat.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
  5. // +----------------------------------------------------------------------
  6. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  7. // +----------------------------------------------------------------------
  8. // | Author: CRMEB Team <admin@crmeb.com>
  9. // +----------------------------------------------------------------------
  10. // #ifdef H5
  11. import WechatJSSDK from "@/plugin/jweixin-module/index.js";
  12. import {getWechatConfig,wechatAuth} from "@/api/public";
  13. import util from 'utils/util'
  14. import {
  15. WX_AUTH,
  16. STATE_KEY,
  17. LOGINTYPE,
  18. BACK_URL
  19. } from '@/config/cache';
  20. import {parseQuery} from '@/utils';
  21. import store from '@/store';
  22. import Cache from '@/utils/cache';
  23. class AuthWechat {
  24. constructor() {
  25. //微信实例化对象
  26. this.instance = WechatJSSDK;
  27. //是否实例化
  28. this.status = false;
  29. this.initConfig = {};
  30. }
  31. isAndroid(){
  32. let u = navigator.userAgent;
  33. return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  34. }
  35. signLink() {
  36. if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
  37. window.entryUrl = location.href.split('#')[0]
  38. }
  39. let uuu = /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl
  40. return uuu;
  41. }
  42. /**
  43. * 初始化wechat(分享配置)
  44. */
  45. wechat() {
  46. return new Promise((resolve, reject) => {
  47. // if (this.status && !this.isAndroid()) return resolve(this.instance);
  48. getWechatConfig()
  49. .then(res => {
  50. this.instance.config(res.data);
  51. this.initConfig = res.data;
  52. this.status = true;
  53. this.instance.ready(() => {
  54. resolve(this.instance);
  55. })
  56. }).catch(err => {
  57. console.log('微信配置失败',err);
  58. util.Tips({
  59. title: '请正确配置公众号后使用!'+err
  60. });
  61. this.status = false;
  62. reject(err);
  63. });
  64. });
  65. }
  66. /**
  67. * 验证是否初始化
  68. */
  69. verifyInstance() {
  70. let that = this;
  71. return new Promise((resolve, reject) => {
  72. if (that.instance === null && !that.status) {
  73. that.wechat().then(res => {
  74. resolve(that.instance);
  75. }).catch(() => {
  76. return reject();
  77. })
  78. } else {
  79. return resolve(that.instance);
  80. }
  81. })
  82. }
  83. // 微信公众号的共享地址
  84. openAddress() {
  85. uni.showLoading({
  86. title: '加载中...'
  87. });
  88. return new Promise((resolve, reject) => {
  89. this.wechat().then(wx => {
  90. this.toPromise(wx.openAddress).then(res => {
  91. uni.hideLoading();
  92. resolve(res);
  93. }).catch(err => {
  94. uni.hideLoading();
  95. reject(err);
  96. });
  97. }).catch(err => {
  98. uni.hideLoading();
  99. reject(err);
  100. })
  101. });
  102. }
  103. // 获取经纬度;
  104. location(){
  105. return new Promise((resolve, reject) => {
  106. this.wechat().then(wx => {
  107. this.toPromise(wx.getLocation,{type: 'wgs84'}).then(res => {
  108. resolve(res);
  109. }).catch(err => {
  110. reject(err);
  111. });
  112. }).catch(err => {
  113. reject(err);
  114. })
  115. });
  116. }
  117. // 使用微信内置地图查看位置接口;
  118. seeLocation(config){
  119. return new Promise((resolve, reject) => {
  120. this.wechat().then(wx => {
  121. this.toPromise(wx.openLocation, config).then(res => {
  122. resolve(res);
  123. }).catch(err => {
  124. reject(err);
  125. });
  126. }).catch(err => {
  127. reject(err);
  128. })
  129. });
  130. }
  131. /**
  132. * 微信支付
  133. * @param {Object} config
  134. */
  135. pay(config) {
  136. return new Promise((resolve, reject) => {
  137. this.wechat().then((wx) => {
  138. this.toPromise(wx.chooseWXPay, config).then(res => {
  139. resolve(res);
  140. }).catch(res => {
  141. resolve(res);
  142. });
  143. }).catch(res => {
  144. reject(res);
  145. });
  146. });
  147. }
  148. toPromise(fn, config = {}) {
  149. return new Promise((resolve, reject) => {
  150. fn({
  151. ...config,
  152. success(res) {
  153. resolve(res);
  154. },
  155. fail(err) {
  156. reject(err);
  157. },
  158. complete(err) {
  159. reject(err);
  160. },
  161. cancel(err) {
  162. reject(err);
  163. }
  164. });
  165. });
  166. }
  167. /**
  168. * 自动去授权
  169. */
  170. oAuth(snsapiBase,url) {
  171. if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
  172. const {
  173. code
  174. } = parseQuery();
  175. if (!code || code == uni.getStorageSync('snsapiCode')){
  176. return this.toAuth(snsapiBase,url);
  177. }else{
  178. if(Cache.has('snsapiKey'))
  179. return this.auth(code).catch(error=>{
  180. uni.showToast({
  181. title:error,
  182. icon:'none'
  183. })
  184. })
  185. }
  186. // if (uni.getStorageSync(WX_AUTH) && store.state.app.token) return;
  187. // const {
  188. // code
  189. // } = parseQuery();
  190. // if (!code){
  191. // return this.toAuth(snsapiBase,url);
  192. // }else{
  193. // if(Cache.has('snsapiKey'))
  194. // return this.auth(code).catch(error=>{
  195. // uni.showToast({
  196. // title:error,
  197. // icon:'none'
  198. // })
  199. // })
  200. // }
  201. }
  202. clearAuthStatus() {
  203. }
  204. /**
  205. * 授权登录获取token
  206. * @param {Object} code
  207. */
  208. auth(code) {
  209. return new Promise((resolve, reject) => {
  210. wechatAuth(code, Cache.get('spread'))
  211. .then(({
  212. data
  213. }) => {
  214. resolve(data);
  215. Cache.set(WX_AUTH, code);
  216. Cache.clear(STATE_KEY);
  217. // Cache.clear('spread');
  218. loginType && Cache.clear(LOGINTYPE);
  219. })
  220. .catch(reject);
  221. });
  222. }
  223. /**
  224. * 获取跳转授权后的地址
  225. * @param {Object} appId
  226. */
  227. getAuthUrl(appId,snsapiBase,backUrl) {
  228. let url = `${location.origin}${backUrl}`
  229. if(url.indexOf('?') == -1){
  230. url = url+'?'
  231. }else{
  232. url = url+'&'
  233. }
  234. const redirect_uri = encodeURIComponent(
  235. `${url}scope=${snsapiBase}&back_url=` +
  236. encodeURIComponent(
  237. encodeURIComponent(
  238. uni.getStorageSync(BACK_URL) ?
  239. uni.getStorageSync(BACK_URL) :
  240. location.pathname + location.search
  241. )
  242. )
  243. );
  244. uni.removeStorageSync(BACK_URL);
  245. const state = encodeURIComponent(
  246. ("" + Math.random()).split(".")[1] + "authorizestate"
  247. );
  248. uni.setStorageSync(STATE_KEY, state);
  249. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
  250. // if(snsapiBase==='snsapi_base'){
  251. // return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
  252. // }else{
  253. // return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
  254. // }
  255. }
  256. /**
  257. * 跳转自动登录
  258. */
  259. toAuth(snsapiBase,backUrl) {
  260. let that = this;
  261. this.wechat().then(wx => {
  262. location.href = this.getAuthUrl(that.initConfig.appId,snsapiBase,backUrl);
  263. })
  264. }
  265. /**
  266. * 绑定事件
  267. * @param {Object} name 事件名
  268. * @param {Object} config 参数
  269. */
  270. wechatEvevt(name, config) {
  271. let that = this;
  272. return new Promise((resolve, reject) => {
  273. let configDefault = {
  274. fail(res) {
  275. if (that.instance) return reject({
  276. is_ready: true,
  277. wx: that.instance
  278. });
  279. that.verifyInstance().then(wx => {
  280. return reject({
  281. is_ready: true,
  282. wx: wx
  283. });
  284. })
  285. },
  286. success(res) {
  287. return resolve(res,2222);
  288. }
  289. };
  290. Object.assign(configDefault, config);
  291. that.wechat().then(wx => {
  292. if (typeof name === 'object') {
  293. name.forEach(item => {
  294. wx[item] && wx[item](configDefault)
  295. })
  296. } else {
  297. wx[name] && wx[name](configDefault)
  298. }
  299. })
  300. });
  301. }
  302. isWeixin() {
  303. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  304. }
  305. }
  306. export default new AuthWechat();
  307. // #endif