request-payment.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const app = getApp()
  2. Page({
  3. onShareAppMessage() {
  4. return {
  5. title: '发起支付',
  6. path: 'packageAPI/pages/api/request-payment/request-payment'
  7. }
  8. },
  9. onLoad() {
  10. this.setData({
  11. theme: wx.getSystemInfoSync().theme || 'light'
  12. })
  13. if (wx.onThemeChange) {
  14. wx.onThemeChange(({theme}) => {
  15. this.setData({theme})
  16. })
  17. }
  18. },
  19. requestPayment() {
  20. const self = this
  21. self.setData({
  22. loading: true
  23. })
  24. // 此处需要先调用wx.login方法获取code,然后在服务端调用微信接口使用code换取下单用户的openId
  25. // 具体文档参考https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html?t=20161230#wxloginobject
  26. app.getUserOpenId(function (err, openid) {
  27. if (!err) {
  28. wx.cloud.callFunction({
  29. name: 'pay',
  30. data: {
  31. theme: 'light',
  32. action: 'unifiedorder',
  33. userInfo: {
  34. openId: openid
  35. },
  36. price: 0.01
  37. },
  38. success: res => {
  39. console.warn('[云函数] [openapi] templateMessage.send 调用成功:', res)
  40. const data = res.result.data
  41. wx.requestPayment({
  42. timeStamp: data.time_stamp,
  43. nonceStr: data.nonce_str,
  44. package: `prepay_id=${data.prepay_id}`,
  45. signType: 'MD5',
  46. paySign: data.sign,
  47. success: () => {
  48. wx.showToast({title: '支付成功'})
  49. },
  50. fail(err) {
  51. self.setData({
  52. loading: false
  53. })
  54. console.error('支付失败:', err)
  55. }
  56. })
  57. },
  58. fail: err => {
  59. wx.showToast({
  60. icon: 'none',
  61. title: '支付失败',
  62. })
  63. console.error('[云函数] [openapi] templateMessage.send 调用失败:', err)
  64. }
  65. })
  66. } else {
  67. console.log('err:', err)
  68. self.setData({
  69. loading: false
  70. })
  71. }
  72. })
  73. }
  74. })