wechat.js 7.4 KB

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