1. 程式人生 > 其它 >前端 微信小程式介面呼叫註冊,圖片介面呼叫

前端 微信小程式介面呼叫註冊,圖片介面呼叫

技術標籤:VUE小程式vue.js

微信小程式介面呼叫註冊及對接微信圖片介面

微信小程式呼叫微信的介面,需要先進行註冊,然後再進行呼叫介面

一、先進行註冊


import {getSign} from "../http/apiService";
import wx from 'weixin-js-sdk';


/**
 *
 * @param url
 * @returns {Promise<number>} 1 代表準備完成
 */
async function getWxSDKSign(url) {
  let status = -1;
  await getSign
(url).then(res => { //後臺返回的加祕簽名 let sign = res.data.data.sign; let timeSign = res.data.data.timestamp; let noncestr = res.data.data.noncestr; wx.config({ beta: true,// 呼叫wx.invoke形式的介面值時,該值必須為true。 debug: false, // 開啟除錯模式,呼叫的所有api的返回值會在客戶端alert出來,若要檢視傳入的引數,可以在pc端開啟,引數資訊會通過log打出,僅在pc端時才會列印。
appId: '', // 必填, timestamp: timeSign, // 必填,微信的cropID填,生成簽名的時間戳 nonceStr: noncestr, // 必填,生成簽名的隨機串 signature: sign,// 必填,簽名,見附錄1 jsApiList: ['chooseImage','getLocalImgData','previewImage','uploadImage','downloadImage','showWatermark'] // 必填,需要使用的JS介面列表,所有JS介面列表見附錄2, /*提取到這裡 請統一註冊*/
}); wx.ready(function () { //準備完成 status = 1; wx.invoke("showWatermark",{},function(res) { //開啟頁面水印 }); }); wx.error(function (res) { //出錯 status = -1; console.log('wx config error: '); console.log(res); }); }).catch(err => { console.log('wx catch error: '); console.log(err); status = 0; }); return status; } export {getWxSDKSign};

其中…/http/apiService 中的getSign 方法如下

import httpManager from "./httpManager";
//獲取微信元件呼叫得簽名 訪問後臺介面獲取簽名
export function getSign(formData) {
  return httpManager({
    url: '/xxxx/xxxx/txSign/getSign',
    method: 'post',
    data: formData
  });
}

apiService中使用到的httpManager.js 如下:

import axios from 'axios';
import router from '../router';
import MyUtils from "../utils/MyUtils";
import Sha256 from "js-sha256";
import {getUrlKey} from '../utils/getUrlKey.js'
//獲取code並且儲存到sessionstorage
let code = getUrlKey('code') || '';
sessionStorage.setItem('code', code);
// alert("code"+code);

// 建立axios例項
const service = axios.create({
  showloader: true,
  timeout: 20000, // 請求超時時間,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  }
});

service.interceptors.request.use(res => {
  // x-tif-paasid:您的(呼叫者)應用的 PaaSID
  // x-tif-signature:您(呼叫者)生成的簽名字串,詳細演算法見“簽名演算法”部分
  // x-tif-timestamp:當前 unix 時間戳
  // x-tif-nonce: 您(呼叫者)生成的非重複的隨機字串(十分鐘內不能重複),用於結合時間戳防止重放
  let timestamp = Date.parse(new Date()) / 1000;
  let nonce = MyUtils.randomString(false, 38);
  let paasid = ''; //您的(呼叫者)應用的 PaaSID
  let token = ''; //應用註冊後獲取的token
  let signature = Sha256.sha256(timestamp + nonce + timestamp);
  res.headers['x-tif-paasid'] = paasid;
  res.headers['x-tif-timestamp'] = timestamp;
  res.headers['x-tif-nonce'] = nonce;
  res.headers['x-tif-signature'] = signature;
  res.headers['token'] = token;
  res.headers['code'] =  sessionStorage.getItem('code')//頭部加入code
  return res;
});
//http request 攔截器
service.interceptors.request.use(
  config => {
    console.log(config)
    config.data = JSON.stringify(config.data);
    // config.headers = {
    //   'Content-Type': 'multipart/form-data;'
    // };
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

//http response 攔截器
service.interceptors.response.use(
  response => {
    console.log(response);
    const resData = response.data;
    return response;
  },
  error => {
    return Promise.reject(error)
  }
);
export default service;

httpManger中使用到的 MyUtils. js如下:

static randomString(randomLen, min, max) {
    let str = "",
      range = min,
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
        'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
        'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    // 隨機產生
    if (randomLen) {
      range = Math.round(Math.random() * (max - min)) + min;
    }
    for (let i = 0; i < range; i++) {
      let pos = Math.round(Math.random() * (arr.length - 1));
      str += arr[pos];
    }
    return str;
  }

static strIsEmpty(str) {
    return typeof str == "undefined" || str == null || str == "";
  }

httpManger中使用到getUrlKey.js 如下:

export  function getUrlKey(name){
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}

至此,微信介面註冊已經完成。

二、微信圖片介面呼叫,將其封裝成一個元件,多個頁面進行呼叫。ImageLoader.vue如下:


<template>
  <div style="background: white">
    <div class="van-uploader" style="margin: 5px 15px;">
      <div ref="wrapper" class="van-uploader__wrapper">
        <div v-for="(item,i) in imageList" class="van-uploader__preview">
          <div class="van-image van-uploader__preview-image" style="overflow: hidden; border-radius: 4px;">
            <img class="van-image__img" style="object-fit: cover;" :src="item.localId">
          </div>
          <i @click="onDeleteImage(i)" class="van-icon van-icon-clear van-uploader__preview-delete"><!----></i>
        </div>
        <div v-if="addShow" @click="onChooseImage" class="van-uploader__upload">
          <i class="van-icon van-icon-plus van-uploader__upload-icon micon"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import wx from 'weixin-js-sdk';
  import MyUtils from "../utils/MyUtils";

  export default {
    name: "ImageLoader",
    props: ['maxCount'],
    data() {
      return {
        imageList: [],
        addShow: true,
        loadingToast: undefined,
      }
    },
    methods: {
      onChooseImage() {
        let that = this;
        let count = this.maxCount - this.imageList.length;
        wx.chooseImage({
          count: count, // 預設9
          sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
          sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
          quality: 0.8,
          success: function (res) {
            // 返回選定照片的本地ID列表,localId可以作為img標籤的src屬性顯示圖片
            for (let i = 0; i < res.localIds.length; i++) {
              let id = res.localIds[i].toString();
              let image = {
                localId: id,
                serverId: '',
              };
              that.imageList.push(image);
            }
            if (that.imageList.length === that.maxCount) {
              that.addShow = false;
            }

            console.log(that.imageList);

            //圖片上傳提示
            that.loadingToast = that.$toast.loading({
              mask: false,
              duration: 0,
              loadingType: 'spinner',
              message: '正在上傳圖片....'
            });

            that.syncUpload(res.localIds)
          }
        });
      },
      onDeleteImage(index) {
        this.imageList.splice(index, 1);
        if (this.imageList.length < this.maxCount) {
          this.addShow = true;
        }
      },
      getServerId() {
        console.log(this.imageList);
        let serverIds = [];
        for (let i = 0; i < this.imageList.length; i++) {
          serverIds.push(this.imageList[i].serverId);
        }
        return serverIds;
      },
      async syncUpload(localIds) {
        let that = this;
        let id = localIds.pop();
        await wx.uploadImage({
          localId: id,
          isShowProgressTips: 0,
          success: function (res) {
            // 返回圖片的伺服器端ID
            let serverId = res.serverId;
            console.log(serverId);

            //講serverId 賦值給 對應的圖片物件
            for (let i = 0; i < that.imageList.length; i++) {
              if (id === that.imageList[i].localId) {
                that.imageList[i].serverId = serverId;
              }
            }
            console.log(that.imageList);
            //繼續提交
            if (localIds.length > 0) {
              that.syncUpload(localIds);
            } else {
              //此時已經整體結束了,關閉loading
              that.loadingToast.clear();
            }
          }
        });
      },
    },
    destroyed() {
    //MyUtils.strIsEmpty() 方法已在上面的MyUtils.js中寫出
      if (!MyUtils.strIsEmpty(this.loadingToast)) {
        this.loadingToast.clear();
      }
    }
  }
</script>

<style scoped>

  .micon {
    content: url("../assets/icon_addphotos.png");
  }

</style>

對ImageLoader.vue進行呼叫 示例:

//部分html程式碼   
  <div class="tt">
        <span class="tt_icon"></span>
        <h4>選擇照片</h4>
      </div>
      <ImageLoader ref="imageLoader" :maxCount="5"></ImageLoader>
      <div style="height: 10 px"></div>
    </div>
    
<script>
import ImageLoader from "../ImageLoader";

//methods中獲取照片的serverIds部分
	let serverIds = this.$refs.imageLoader.getServerId();
</script>

大致介面如下:
在這裡插入圖片描述