微信小程序基本操作

获取openid

步骤

1.用户点击小程序中的登录按钮,该按钮绑定一个登录方法,该方法中执行wx.login接口,该接口将当前用户对应的code传递到服务端
2.服务端拿到传递过来的code后,调用指定接口即可获取openidsession_key信息。

小程序部分

  • index.wxml代码:
<!--index.wxml-->
<view class="container">
  <view>
    <button bindtap="login"> 登录 </button>
  </view>
  <block wx:if="{{openid}}">
  <view>
    <text>你的openid是:{{openid}}</text>
  </view>
  </block>
</view>
  • index.js代码:
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    openid: '',
  },  
  onLoad: function () {
    if (wx.getStorageSync("openId")) {
      this.setData({
        openid: wx.getStorageSync("openId")
      })
    }
  },
  login:function(){
    wx.login({
        success: (res) => {
            console.log('login:code', res.code)
            //发送请求
            wx.request({
              url: 'api.php', //接口地址
              data: {
                  'code': res.code
              },
              header: {
                  'content-type': 'application/json'
              },
              success: (res) => {
                  console.log("record  成功", res.data)
                  if (res.error) { //发生错误
                      console.log("错误:", res.msg);
                  } else { //返回成功
                      try {
                          wx.setStorageSync('openId', res.data.openid) // 全局赋值
                          //openid = wx.getStorageSync("openId"); // 取值
                          console.log(wx.getStorageSync("openId"))
                          this.setData({
                            openid: res.data.openid
                          })
                      } catch (e) {
                          console.log("wx.login 错误", e);
                      }
                  }
              },
              fail: function (err) {
                  console.log("record  失败", err);
              }
          })
        }
    })
  }
})

  • api.php代码如下:
<?php
error_reporting(1);
$appid = 'xxxxx';
$secret = 'xxxxx';

//获取openid
$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&grant_type=authorization_code&js_code=".$_GET['code'];
$result = curlPost($url);
$result = json_decode($result,true);
$data['code'] = 1;
if($result['errcode']){
    $data['error'] = $result['errmsg'];
}else{
    $data['code'] = 0;
    $data['session_key'] = $result['session_key'];
    $data['openid'] = $result['openid'];
}
echo json_encode($data);exit();

function curlPost($url = '', $postData = '', $options = array())
{
    if (is_array($postData)) {
        $postData = http_build_query($postData);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
    if (!empty($options)) {
        curl_setopt_array($ch, $options);
    }
    //https请求 不验证证书和host
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

演示效果截图:

发送订阅消息

步骤

1.添加消息模板,获取模板id
2.获取access_token
3.获取下发权限
详见小程序端消息订阅接口 wx.requestSubscribeMessage
4.调用接口下发订阅消息
详见服务端消息发送接口 subscribeMessage.send

1.获取模板id

2.获取access_token

服务端PHP代码如下:

//获取access_token
$appid = 'xxxxx';
$secret = 'xxxxx';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$result = curlPost($url);
/**
返回格式如下:
{"access_token":"34_Pmv428FIwIQGan-1WRnkXh6HM4QBq4XkyJHgo9Mu_CwFJc2Cp5e2dtWSnVA1hPI2Uklwb2F7X-PEOetzMyfTnCUCv3oZ7rBs-g6LqtgApel4l7PEMEFKA1EBVLpC4c9M4EQc3JiDus5AeBQ2IXZfAEASHJ","expires_in":7200}
**/
$result = json_decode($result,true);
$token = $result['access_token'];

3.获取下发权限

小程序段代码:
* index.wxml代码:

<view class="container">
  <view>
    <button bindtap="subscibe"> 订阅消息 </button>
  </view>
  <block wx:if="{{isSubscibe}}">
  <view>
    <text>你已订阅</text>
  </view>
  </block>
  <block wx:else>
  <view>
    <text>未订阅</text>
  </view>
  </block>
</view>
  • index.js代码:
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    isSubscibe: false,  //是否已订阅
  },
  subscibe:function(){
    return new Promise((resolve, reject) => {
      wx.requestSubscribeMessage({
          tmplIds: ["llhQ8dJ_AkKpwbL-PUCbADl42UwomhRPURx-RkuBAxI"],
          success: (res) => {
              if (res['llhQ8dJ_AkKpwbL-PUCbADl42UwomhRPURx-RkuBAxI'] === 'accept') {
                this.setData({
                  isSubscibe: true
                })
                wx.showToast({
                    title: '订阅OK!',
                    duration: 1000,
                    success(data) {
                        //成功
                        resolve()
                    }
                })
              }
          },
          fail(err) {
              //失败
              console.error(err);
              reject()
          }
      })
    })
  }
})

4.调用接口下发订阅消息

//发送消息
$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$token;
$postData['access_token'] =  $token;
$postData['touser'] =  $openid;
$postData['template_id'] =  'llhQ8dJ_AkKpwbL-PUCbADl42UwomhRPURx-RkuBAxI';  //模板ID
$postData['page'] =  'https://www.baidu.com';
$postData['data'] =  [
  'thing1'=>[
      'value'=>'每日签到'
  ],
  'thing2'=>[
      'value'=>'点击立即签到'
  ],
  'name3'=>[
      'value'=>'周杰伦'
  ],
  'date4'=>[
      'value'=>date('Y-m-d')
  ],
  'time5'=>[
      'value'=>date('H:i:s')
  ],
];
$result = curlPost($url,json_encode($postData,JSON_UNESCAPED_UNICODE));

效果演示:

发表评论

邮箱地址不会被公开。 必填项已用*标注