index.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <template>
  2. <view style="z-index: 999;">
  3. <uni-popup ref="popup" :is-mask-click="false" borderRadius="10px 10px 0 0" background-color="#eee" @change="popupChange">
  4. <view class="popup-content">
  5. <view class="popup-content-close">
  6. <view class="icon" @tap="closePayPopup">
  7. <uni-icons
  8. type="closeempty"
  9. color="#999"
  10. size="24"
  11. />
  12. </view>
  13. </view>
  14. <view class="popup-content-main">
  15. <view class="popup-content-main-count">
  16. <view class="title">{{ title }}</view>
  17. <view class="pay">
  18. <uni-icons color="#000" type="icon-renminbi1688" size="16" custom-prefix="iconfont"></uni-icons>
  19. <view>{{ amount }}</view>
  20. </view>
  21. </view>
  22. <view class="popup-content-main-type">
  23. <view v-if="payTypeList?.length" class="card">
  24. <radio-group @change="radioChange">
  25. <label class="card-label" v-for="item in payTypeList" :key="item.value">
  26. <view class="name">
  27. <uni-icons :color="item.color" class="mr-1" :type="item.icon" size="24" custom-prefix="iconfont"></uni-icons>
  28. {{item.name}}
  29. </view>
  30. <view>
  31. <radio :value="item.value" :disabled="item.disabled" :checked="item.value === channelValue" />
  32. </view>
  33. </label>
  34. </radio-group>
  35. </view>
  36. </view>
  37. </view>
  38. <view class="popup-content-btn">
  39. <button class="popup-content-btn-s" @tap="handlePay(false)">
  40. 确认支付
  41. <uni-icons color="#FFF" type="icon-renminbi1688" size="16" custom-prefix="iconfont"></uni-icons>
  42. {{ amount }}
  43. </button>
  44. </view>
  45. </view>
  46. </uni-popup>
  47. </view>
  48. </template>
  49. <script setup>
  50. import { ref } from 'vue'
  51. import { onHide, onShow } from '@dcloudio/uni-app'
  52. // import { userStore } from '@/store/user'; const useUserStore = userStore()
  53. import { getSocialUser, socialUserBind, payOrderSubmit, getOrderPayStatus, getEnableCodeList } from '@/api/common'
  54. import { createTradeOrder, getUnpaidOrder } from '@/api/new/position'
  55. const emit = defineEmits(['paySuccess', 'close'])
  56. const props = defineProps({
  57. title: { // 标题
  58. type: String,
  59. default: '支付'
  60. },
  61. })
  62. const payType = [
  63. {
  64. name: '微信支付',
  65. value: 'wx_lite',
  66. icon: 'icon-weixinzhifu',
  67. color: '#1AAD19'
  68. },
  69. // {
  70. // name: '钱包支付',
  71. // value: 'wallet',
  72. // disabled: true,
  73. // icon: 'icon-qianbao1',
  74. // color: '#00B760'
  75. // }
  76. ]
  77. // 余额和其他还没有接暂时只支持微信支付
  78. const payTypeList = ref([])
  79. // 获取支付方式
  80. const getPayMethodsList = async () => {
  81. console.log('获取支付方式:', )
  82. payTypeList.value = []
  83. try {
  84. const res = await getEnableCodeList({appId: 10})
  85. if (!res?.data?.length) {
  86. return
  87. }
  88. payTypeList.value.push(...payType.filter(e => res.data.includes(e.value)))
  89. const result = payType.find(item => !item.disabled && item.value)
  90. if (result) channelValue.value = result.value
  91. } catch (error) {
  92. console.log(error)
  93. }
  94. }
  95. const channelValue = ref('')
  96. const radioChange = (e) => {
  97. channelValue.value = e?.detail?.value || ''
  98. }
  99. const tabBarShow = (show = false) => { // 显示/隐藏 TabBar
  100. console.log('tabBarShow:', show ? '展示' : '隐藏')
  101. const currentPage = getCurrentPages()
  102. if (!currentPage) return
  103. const currentTabBar = currentPage[0]?.getTabBar?.()
  104. currentTabBar?.setData({ show })
  105. }
  106. const popup = ref()
  107. const closePayPopup = () => {
  108. tabBarShow(true)
  109. popup.value.close()
  110. emit('close')
  111. }
  112. const query = ref(null)
  113. const amount = ref('') // 支付金额
  114. const handleOpen = async (val) => {
  115. console.log('handleOpen打开支付:', )
  116. await getPayMethodsList()
  117. query.value = val
  118. amount.value = Number(val?.price) ? Number(val?.price)/100 : 0
  119. tabBarShow(false)
  120. popup.value.open('bottom')
  121. }
  122. // 设置 openid 到本地存储,目前只有 pay 支付时会使用
  123. const setOpenid = (openid) => {
  124. uni.setStorageSync('openid', openid)
  125. }
  126. const bind = () => {
  127. return new Promise(async (resolve, reject) => {
  128. // 1. 获得微信 code
  129. const codeResult = await uni.login()
  130. if (codeResult.errMsg !== 'login:ok') {
  131. return resolve(false)
  132. }
  133. // 2. 绑定账号 // // 社交快捷登录
  134. const obj = {
  135. type: socialType,
  136. code: codeResult.code,
  137. state: 'default',
  138. }
  139. const bindResult = await socialUserBind(obj);
  140. if (bindResult.code === 0) {
  141. setOpenid(bindResult.data)
  142. return resolve(true)
  143. } else {
  144. return resolve(false)
  145. }
  146. })
  147. }
  148. const bindWeiXin = () => {
  149. uni.showModal({
  150. title: '微信支付',
  151. content: '请先绑定微信再使用微信支付',
  152. success: function (res) {
  153. if (res.confirm) {
  154. // 微信小程序绑定
  155. bind()
  156. }
  157. },
  158. });
  159. }
  160. const socialType = 34; // 社交类型 - 微信小程序
  161. // 预支付
  162. const prepay = async (channel, orderData) => {
  163. console.log('预支付prepay:', )
  164. return new Promise(async (resolve, reject) => {
  165. let data = {
  166. id: orderData?.payOrder?.id,
  167. channelCode: channel,
  168. channelExtras: {},
  169. };
  170. // 特殊逻辑:微信公众号、小程序支付时,必须传入 openid
  171. if (['wx_pub', 'wx_lite'].includes(channel)) {
  172. const userRes = await getSocialUser(socialType)
  173. const openid = userRes?.data?.openid ? userRes.data.openid : null
  174. // 如果获取不到 openid,微信无法发起支付,此时需要引导
  175. if (!openid) {
  176. bindWeiXin()
  177. return
  178. }
  179. data.channelExtras.openid = openid
  180. }
  181. // 发起预支付 API 调用
  182. payOrderSubmit(data).then((res) => {
  183. // 成功时
  184. res.code === 0 && resolve(res)
  185. // 失败时
  186. if (res.code !== 0 && res.msg.indexOf('无效的openid') >= 0) {
  187. // 特殊逻辑:微信公众号、小程序支付时,必须传入 openid 不正确的情况
  188. if (
  189. res.msg.indexOf('无效的openid') >= 0 || // 获取的 openid 不正确时,或者随便输入了个 openid
  190. res.msg.indexOf('下单账号与支付账号不一致') >= 0
  191. ) {
  192. bindWeiXin()
  193. }
  194. }
  195. })
  196. })
  197. }
  198. let interTimer = null
  199. let payLoading = false
  200. const checkPayStatus = async (id) => {
  201. console.log('轮询支付状态:调用')
  202. if (pageHide.value) {
  203. console.log('轮询支付状态:页面隐藏:return')
  204. return
  205. }
  206. if (!id) return
  207. uni.showLoading({ title: '加载中' })
  208. try {
  209. if (payLoading || !interTimer) return
  210. payLoading = true
  211. const res = await getOrderPayStatus({ id })
  212. if (res?.data?.status === 10) {
  213. console.log('轮询支付状态:支付成功', res.data.status)
  214. if (interTimer) clearInterval(interTimer); interTimer = null
  215. uni.showToast({ title: '支付成功', icon: 'none'})
  216. setTimeout(async () => {
  217. emit('paySuccess')
  218. closePayPopup()
  219. }, 1500)
  220. }
  221. } catch (error) {
  222. console.log('轮询支付状态:error', error)
  223. if (interTimer) clearInterval(interTimer)
  224. } finally {
  225. payLoading = false
  226. uni.hideLoading()
  227. }
  228. }
  229. // 计时器
  230. const initIntervalFun = () => {
  231. console.log('计时器initIntervalFun:', )
  232. if (interTimer) clearInterval(interTimer)
  233. // 查询是否已经支付
  234. const id = orderInfo.value?.payOrder?.id || orderInfo.value?.order?.payOrderId
  235. if (id) {
  236. interTimer = setInterval(() => {
  237. checkPayStatus(id)
  238. }, 1000)
  239. }
  240. }
  241. const orderInfo = ref({})
  242. const weChatMiniProgramPay = async () => {
  243. console.log('weChatMiniProgramPay调用微信小程序支付')
  244. let res = await prepay(channelValue.value, orderInfo.value); // 预支付
  245. if (res?.code !== 0) {
  246. return;
  247. }
  248. // 调用微信小程序支付
  249. const payConfig = res?.data?.displayContent ? JSON.parse(res.data.displayContent) : null
  250. if (!payConfig) return uni.showToast({ title: '购买失败', icon: 'none'})
  251. uni.requestPayment({
  252. provider: 'wxpay',
  253. timeStamp: payConfig.timeStamp,
  254. nonceStr: payConfig.nonceStr,
  255. package: payConfig.packageValue,
  256. signType: 'RSA',
  257. paySign: payConfig.paySign,
  258. success: (res) => {
  259. // 用户支付成功
  260. console.log('用户支付成功')
  261. initIntervalFun()
  262. // closePayPopup()
  263. },
  264. fail: (err) => {
  265. if (err.errMsg === 'requestPayment:fail cancel') {
  266. uni.showToast({ title: '支付已取消', icon: 'none'})
  267. } else {
  268. uni.showToast({ title: '支付失败', icon: 'none'})
  269. }
  270. },
  271. });
  272. }
  273. // 确认支付
  274. const handlePay = async (retry = false) => {
  275. console.log('确认支付handlePay:', )
  276. if (!channelValue.value) {
  277. uni.showToast({ title: '请选择支付方式', icon: 'none'})
  278. return
  279. }
  280. // 判断是否已有创建好的订单,有就直接跳转支付,没有就创建订单
  281. try {
  282. const params = {
  283. spuId: query.value?.spuId, // 商品编号
  284. type: query.value?.type // 订单类型 0平台订单|1发布职位|2发布众聘职位|3会员套餐|4企业会员套餐|5招聘会门票
  285. }
  286. if (!params.spuId || params.type === null || params.type === undefined) return
  287. const res = await getUnpaidOrder(params) // 1.查询订单
  288. if (res?.data) {
  289. orderInfo.value = res.data
  290. // 微信小程序支付
  291. weChatMiniProgramPay(res.data)
  292. return
  293. }
  294. if (!retry) setOrderCreated() // 2.创建订单
  295. } catch (error) {
  296. console.log(error)
  297. }
  298. }
  299. // 创建订单
  300. const setOrderCreated = async () => {
  301. console.log('setOrderCreated-createTradeOrder:', )
  302. const params = {
  303. spuId: query.value?.spuId, // 商品编号
  304. type: query.value?.type, // 订单类型 0平台订单|1发布职位|2发布众聘职位|3会员套餐|4企业会员套餐|5招聘会门票
  305. price: query.value?.price, // 价格
  306. spuName: query.value?.spuName, // 商品名称
  307. }
  308. if (!params.spuId || params.type === null || params.type === undefined || !params.price || !params.spuName) return
  309. await createTradeOrder(params)
  310. handlePay(true) // 避免死循环
  311. }
  312. const pageHide = ref(false)
  313. onShow(() => {
  314. console.log('onShow')
  315. pageHide.value = false
  316. })
  317. onHide(() => {
  318. console.log('onHide')
  319. pageHide.value = true
  320. closePayPopup() // 关闭支付弹窗
  321. })
  322. const popupChange = (e) => {
  323. console.log('popupChange:', )
  324. if (!e || e.show === undefined) return
  325. if (e.show) {
  326. // 支付弹窗打开
  327. tabBarShow(false)
  328. } else {
  329. // 支付弹窗关闭
  330. tabBarShow(true)
  331. if (interTimer) clearInterval(interTimer)
  332. }
  333. }
  334. defineExpose({
  335. handleOpen
  336. })
  337. </script>
  338. <style lang="scss" scoped>
  339. .pay {
  340. position: sticky;
  341. bottom: 0;
  342. padding: 0 40rpx 50rpx 40rpx;
  343. box-sizing: border-box;
  344. &-box {
  345. width: 100%;
  346. background: linear-gradient(121deg,#fde2c2 29.02%,#c19164 104.03%);
  347. border-radius: 180rpx 0 180rpx 0;
  348. box-shadow: 3rpx 6rpx 10rpx 0rpx rgb(216 160 82);
  349. display: flex;
  350. justify-content: space-between;
  351. align-items: center;
  352. height: 100rpx;
  353. .price {
  354. padding: 0 40rpx;
  355. font-size: 40rpx;
  356. font-weight: 600;
  357. color: #e68735;
  358. }
  359. .btn {
  360. height: 100%;
  361. display: flex;
  362. align-items: center;
  363. padding: 0 40rpx;
  364. border: 2rpx solid #00B760;
  365. background: #00B760;
  366. color: #FFF;
  367. border-radius: 180rpx 0 180rpx 0;
  368. position: relative;
  369. // &::after {
  370. // content: '';
  371. // position: absolute;
  372. // width: 50rpx;
  373. // height: 50rpx;
  374. // background: radial-gradient(top right, transparent 50%, #00B760 50%);
  375. // left: 0;
  376. // top: 0;
  377. // margin-left: -25rpx;
  378. // border-radius: 180rpx;
  379. // }
  380. }
  381. }
  382. }
  383. .popup-content {
  384. z-index: 999;
  385. max-height: 500px;
  386. display: flex;
  387. flex-direction: column;
  388. &-close {
  389. display: flex;
  390. padding: 10px;
  391. justify-content: flex-end;
  392. .icon {
  393. width: 30px;
  394. height: 30px;
  395. background: #ccc;
  396. border-radius: 30px;
  397. display: flex;
  398. align-items: center;
  399. justify-content: center;
  400. }
  401. }
  402. &-main {
  403. flex: 1;
  404. height: 0;
  405. overflow-y: auto;
  406. &-count {
  407. margin-bottom: 20px;
  408. text-align: center;
  409. .title {
  410. font-size: 28rpx;
  411. color: #666
  412. }
  413. .pay {
  414. font-size: 52rpx;
  415. color: #000;
  416. font-weight: 600;
  417. display: flex;
  418. align-items: center;
  419. justify-content: center;
  420. padding: 10px 0;
  421. }
  422. }
  423. &-type {
  424. width: 100%;
  425. padding: 0 20px;
  426. box-sizing: border-box;
  427. .card {
  428. border-radius: 10px;
  429. margin: 0 auto;
  430. background: #FFF;
  431. padding: 10px;
  432. &-label {
  433. padding: 15px 0;
  434. box-sizing: border-box;
  435. display: flex;
  436. justify-content: space-between;
  437. border-bottom: 1px solid #eee;
  438. &:last-of-type {
  439. border-bottom: none;
  440. }
  441. .name {
  442. display: flex;
  443. align-items: center;
  444. color: #333;
  445. }
  446. }
  447. }
  448. }
  449. }
  450. &-btn {
  451. height: 70px;
  452. width: 100%;
  453. margin-top: 10px;
  454. display: flex;
  455. align-items: center;
  456. justify-content: center;
  457. &-s {
  458. height: 40px;
  459. width: 75%;
  460. line-height: 40px;
  461. color: #FFF;
  462. // color: #724d2b;
  463. background: #00B760;
  464. // background: linear-gradient(121deg,#fde2c2 29.02%,#c19164 104.03%);
  465. border-radius: 90px;
  466. }
  467. }
  468. }
  469. .mr-1 {
  470. margin-right: 10px;
  471. }
  472. </style>