index.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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="handleClose">
  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. getPayMethodsList()
  96. const channelValue = ref('')
  97. const radioChange = (e) => {
  98. channelValue.value = e?.detail?.value || ''
  99. }
  100. const tabBarShow = (show = false) => { // 显示/隐藏TabBar
  101. console.log('tabBarShow:', )
  102. const currentPage = getCurrentPages()
  103. if (!currentPage) return
  104. const currentTabBar = currentPage[0]?.getTabBar?.()
  105. currentTabBar?.setData({ show })
  106. }
  107. const popup = ref()
  108. const handleClose = () => {
  109. tabBarShow(true)
  110. popup.value.close()
  111. emit('close')
  112. }
  113. const query = ref(null)
  114. const amount = ref('') // 支付金额
  115. const handleOpen = (val) => {
  116. console.log('handleOpen:', )
  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('checkPayStatus:', )
  202. if (!id) return
  203. uni.showLoading({ title: '加载中' })
  204. try {
  205. if (payLoading || !interTimer) return
  206. payLoading = true
  207. const res = await getOrderPayStatus({ id })
  208. if (res?.data?.status === 10) {
  209. handleClose()
  210. if (interTimer) clearInterval(interTimer)
  211. uni.hideLoading()
  212. uni.showToast({ title: '支付成功', icon: 'none'})
  213. setTimeout(async () => {
  214. emit('paySuccess')
  215. }, 1500)
  216. }
  217. } catch (error) {
  218. console.log(error)
  219. handleClose()
  220. uni.hideLoading()
  221. if (interTimer) clearInterval(interTimer)
  222. } finally {
  223. payLoading = false
  224. }
  225. }
  226. // 计时器
  227. const initIntervalFun = () => {
  228. console.log('计时器initIntervalFun:', )
  229. if (interTimer) clearInterval(interTimer)
  230. // 查询是否已经支付
  231. const id = orderInfo.value?.payOrder?.id || orderInfo.value?.order?.payOrderId
  232. if (id) {
  233. interTimer = setInterval(() => {
  234. checkPayStatus(id)
  235. }, 1000)
  236. }
  237. }
  238. const orderInfo = ref({})
  239. const weChatMiniProgramPay = async (data) => {
  240. console.log('weChatMiniProgramPay:', )
  241. orderInfo.value = data
  242. let res = await prepay(channelValue.value, data); // 预支付
  243. if (res?.code !== 0) {
  244. return;
  245. }
  246. // 调用微信小程序支付
  247. const payConfig = res?.data?.displayContent ? JSON.parse(res.data.displayContent) : null
  248. if (!payConfig) return uni.showToast({ title: '购买失败', icon: 'none'})
  249. uni.requestPayment({
  250. provider: 'wxpay',
  251. timeStamp: payConfig.timeStamp,
  252. nonceStr: payConfig.nonceStr,
  253. package: payConfig.packageValue,
  254. signType: 'RSA',
  255. paySign: payConfig.paySign,
  256. success: (res) => {
  257. // 用户支付成功
  258. initIntervalFun()
  259. // handleClose()
  260. },
  261. fail: (err) => {
  262. if (err.errMsg === 'requestPayment:fail cancel') {
  263. uni.showToast({ title: '支付已取消', icon: 'none'})
  264. } else {
  265. uni.showToast({ title: '支付失败', icon: 'none'})
  266. }
  267. },
  268. });
  269. }
  270. // 确认支付
  271. const handlePay = async (retry = false) => {
  272. console.log('确认支付handlePay:', )
  273. if (!channelValue.value) {
  274. uni.showToast({ title: '请选择支付方式', icon: 'none'})
  275. return
  276. }
  277. // 判断是否已有创建好的订单,有就直接跳转支付,没有就创建订单
  278. try {
  279. const params = {
  280. spuId: query.value?.spuId, // 商品编号
  281. type: query.value?.type // 订单类型 0平台订单|1发布职位|2发布众聘职位|3会员套餐|4企业会员套餐|5招聘会门票
  282. }
  283. if (!params.spuId || params.type === null || params.type === undefined) return
  284. const res = await getUnpaidOrder(params) // 查询订单
  285. if (res.data) {
  286. // 获取支付码
  287. weChatMiniProgramPay(res.data)
  288. return
  289. }
  290. if (!retry) setOrderCreated() // 创建订单
  291. } catch (error) {
  292. console.log(error)
  293. }
  294. }
  295. const setOrderCreated = async () => {
  296. console.log('setOrderCreated-createTradeOrder:', )
  297. const params = {
  298. spuId: query.value?.spuId, // 商品编号
  299. type: query.value?.type, // 订单类型 0平台订单|1发布职位|2发布众聘职位|3会员套餐|4企业会员套餐|5招聘会门票
  300. price: query.value?.price, // 价格
  301. spuName: query.value?.spuName, // 商品名称
  302. }
  303. if (!params.spuId || params.type === null || params.type === undefined || !params.price || !params.spuName) return
  304. await createTradeOrder(params)
  305. handlePay(true) // 避免死循环
  306. }
  307. onShow(() => {
  308. if (orderInfo && orderInfo.value?.id) initIntervalFun()
  309. })
  310. onHide(() => {
  311. if (interTimer) clearInterval(interTimer)
  312. })
  313. const popupChange = (e) => {
  314. console.log('popupChange:', )
  315. if (!e || e.show === undefined) return
  316. if (e.show) {
  317. // 支付弹窗打开
  318. tabBarShow(false)
  319. if (orderInfo && orderInfo.value?.id) initIntervalFun()
  320. } else {
  321. // 支付弹窗关闭
  322. tabBarShow(true)
  323. if (interTimer) clearInterval(interTimer)
  324. }
  325. }
  326. defineExpose({
  327. handleOpen
  328. })
  329. </script>
  330. <style lang="scss" scoped>
  331. .pay {
  332. position: sticky;
  333. bottom: 0;
  334. padding: 0 40rpx 50rpx 40rpx;
  335. box-sizing: border-box;
  336. &-box {
  337. width: 100%;
  338. background: linear-gradient(121deg,#fde2c2 29.02%,#c19164 104.03%);
  339. border-radius: 180rpx 0 180rpx 0;
  340. box-shadow: 3rpx 6rpx 10rpx 0rpx rgb(216 160 82);
  341. display: flex;
  342. justify-content: space-between;
  343. align-items: center;
  344. height: 100rpx;
  345. .price {
  346. padding: 0 40rpx;
  347. font-size: 40rpx;
  348. font-weight: 600;
  349. color: #e68735;
  350. }
  351. .btn {
  352. height: 100%;
  353. display: flex;
  354. align-items: center;
  355. padding: 0 40rpx;
  356. border: 2rpx solid #00B760;
  357. background: #00B760;
  358. color: #FFF;
  359. border-radius: 180rpx 0 180rpx 0;
  360. position: relative;
  361. // &::after {
  362. // content: '';
  363. // position: absolute;
  364. // width: 50rpx;
  365. // height: 50rpx;
  366. // background: radial-gradient(top right, transparent 50%, #00B760 50%);
  367. // left: 0;
  368. // top: 0;
  369. // margin-left: -25rpx;
  370. // border-radius: 180rpx;
  371. // }
  372. }
  373. }
  374. }
  375. .popup-content {
  376. z-index: 999;
  377. max-height: 500px;
  378. display: flex;
  379. flex-direction: column;
  380. &-close {
  381. display: flex;
  382. padding: 10px;
  383. justify-content: flex-end;
  384. .icon {
  385. width: 30px;
  386. height: 30px;
  387. background: #ccc;
  388. border-radius: 30px;
  389. display: flex;
  390. align-items: center;
  391. justify-content: center;
  392. }
  393. }
  394. &-main {
  395. flex: 1;
  396. height: 0;
  397. overflow-y: auto;
  398. &-count {
  399. margin-bottom: 20px;
  400. text-align: center;
  401. .title {
  402. font-size: 28rpx;
  403. color: #666
  404. }
  405. .pay {
  406. font-size: 52rpx;
  407. color: #000;
  408. font-weight: 600;
  409. display: flex;
  410. align-items: center;
  411. justify-content: center;
  412. padding: 10px 0;
  413. }
  414. }
  415. &-type {
  416. width: 100%;
  417. padding: 0 20px;
  418. box-sizing: border-box;
  419. .card {
  420. border-radius: 10px;
  421. margin: 0 auto;
  422. background: #FFF;
  423. padding: 10px;
  424. &-label {
  425. padding: 15px 0;
  426. box-sizing: border-box;
  427. display: flex;
  428. justify-content: space-between;
  429. border-bottom: 1px solid #eee;
  430. &:last-of-type {
  431. border-bottom: none;
  432. }
  433. .name {
  434. display: flex;
  435. align-items: center;
  436. color: #333;
  437. }
  438. }
  439. }
  440. }
  441. }
  442. &-btn {
  443. height: 70px;
  444. width: 100%;
  445. margin-top: 10px;
  446. display: flex;
  447. align-items: center;
  448. justify-content: center;
  449. &-s {
  450. height: 40px;
  451. width: 75%;
  452. line-height: 40px;
  453. color: #FFF;
  454. // color: #724d2b;
  455. background: #00B760;
  456. // background: linear-gradient(121deg,#fde2c2 29.02%,#c19164 104.03%);
  457. border-radius: 90px;
  458. }
  459. }
  460. }
  461. .mr-1 {
  462. margin-right: 10px;
  463. }
  464. </style>