微信步数获取-PHP后端部分

官网地址

[https://developers.weixin.qq.com/miniprogram/dev/api/open-api/werun/wx.getWeRunData.html
]

前端调取微信接口拿到的数据需要后台解密,解密需要的参数有encryptedDataiv以及code
code的作用是用来获取用户的sessionKey即会话密钥
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

类代码如下
appid = $wechat['appkey'];
           $this->appsecret = $wechat['appsecret'];
           $this->sessionKey = $this->getSessionKey($code);

    }


    /**
     * 检验数据的真实性,并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0,失败返回对应的错误码
     */
    public function decryptData( $encryptedData, $iv, &$data )
    {
        if (strlen($this->sessionKey) != 24) {
            return ErrorCode::$IllegalAesKey;
        }
        $aesKey=base64_decode($this->sessionKey);

        
        if (strlen($iv) != 24) {
            return ErrorCode::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return ErrorCode::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return ErrorCode::$IllegalBuffer;
        }
        $data = $result;
        return ErrorCode::$OK;
    }

    public function getSessionKey($code)
    {

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->appsecret.'&js_code='.$code.'&grant_type=authorization_code';

        $data = self::http_request($url);

        $data = json_decode($data,true);
        if($data['errcode'] == 0){
            $sessinKay = $data['session_key'];
        }else{
            ajaxError('获取步数失败',$data['errmsg']);
        }

        return $sessinKay;
    }

}


ErrorCode


 *    
  • -41001: encodingAesKey 非法
  • *
  • -41003: aes 解密失败
  • *
  • -41004: 解密后得到的buffer非法
  • *
  • -41005: base64加密失败
  • *
  • -41016: base64解密失败
  • * */ class ErrorCode { public static $OK = 0; public static $IllegalAesKey = -41001; public static $IllegalIv = -41002; public static $IllegalBuffer = -41003; public static $DecodeBase64Error = -41004; } ?>
    调用
      public static function getStep($input)
      {
          $pc = new WXBizDataCrypt($input['code']);
          $errCode = $pc->decryptData($input['encryptedData'], $input['iv'], $data );
          if ($errCode == 0) {
              $stepList = json_decode($data,true);
              return $stepList
           } else {
              $result['error'] = $errCode;
              return $result;
          }
      }
    

    你可能感兴趣的:(微信步数获取-PHP后端部分)