Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Woocommerce api rest v2签名不匹配_Java_Api_Woocommerce_Signature - Fatal编程技术网

Java Woocommerce api rest v2签名不匹配

Java Woocommerce api rest v2签名不匹配,java,api,woocommerce,signature,Java,Api,Woocommerce,Signature,我正在尝试调用woocommerce的其余api,在这里您可以看到我调用它的代码,我有oauth nonce、时间戳、密钥和密码,并生成签名。我得到这个错误 {"errors":[{"code":"woocommerce_api_authentication_error","message":"Firma incorrecta - No coindicen las firmas"}]} 签名不正确,签名不匹配 public class Woocommerce { private static

我正在尝试调用woocommerce的其余api,在这里您可以看到我调用它的代码,我有oauth nonce、时间戳、密钥和密码,并生成签名。我得到这个错误

{"errors":[{"code":"woocommerce_api_authentication_error","message":"Firma incorrecta - No coindicen las firmas"}]}
签名不正确,签名不匹配

public class Woocommerce {

private static String key = "ck_c6f7ea09138c------";
private static String secret = "cs_ed5c525f563dff-----";

private static final String HMAC_SHA1 = "HmacSHA1";

private static final String ENC = "UTF-8";

private static Base64 base64 = new Base64();

private static String getSignature(String url, String params)
        throws UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {

    StringBuilder base = new StringBuilder();
    base.append("GET&");
    base.append(url);
    base.append("&");
    base.append(params);
    System.out.println("creating signature..." + base);

    byte[] keyBytes = (secret + "&").getBytes(ENC);

    SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);

    Mac mac = Mac.getInstance(HMAC_SHA1);
    mac.init(key);

    return new String(base64.encode(mac.doFinal(base.toString().getBytes(
            ENC))), ENC).trim();
}

public static void main(String[] args) throws ClientProtocolException,
        IOException, URISyntaxException, InvalidKeyException,
        NoSuchAlgorithmException {

    HttpClient httpclient = new DefaultHttpClient();
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    // These params should ordered in key

    qparams.add(new BasicNameValuePair("oauth_consumer_key", key));
    qparams.add(new BasicNameValuePair("oauth_nonce", ""
            + (int) (Math.random() * 100000000)));
    qparams.add(new BasicNameValuePair("oauth_signature_method",
            "HMAC-SHA1"));
    qparams.add(new BasicNameValuePair("oauth_timestamp", ""
            + (System.currentTimeMillis() / 1000)));

    // generate the oauth_signature

    String signature = getSignature(
            URLEncoder.encode("www.buhoplace.net", ENC),
            URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));
    // add it to params list
    qparams.add(new BasicNameValuePair("oauth_signature", signature));

    // generate URI which lead to access_token and token_secret.
    URI uri = URIUtils.createURI("http", "www.buhoplace.net", -1,
            "/wc-api/v2/products", URLEncodedUtils.format(qparams, ENC),
            null);

    System.out.println("url llamada" + uri);

    HttpGet httpget = new HttpGet(uri);
    // output the response content.
    System.out.println("Resultado de la llamada");

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        int len;
        byte[] tmp = new byte[2048];
        while ((len = instream.read(tmp)) != -1) {
            System.out.println(new String(tmp, 0, len, ENC));
        }
    }
}
公共类商业{
私有静态字符串key=“ck_c6f7ea09138c------”;
私有静态字符串secret=“cs_ed5c525f563dff-----”;
私有静态最终字符串HMAC_SHA1=“HmacSHA1”;
专用静态最终字符串ENC=“UTF-8”;
私有静态Base64 Base64=新Base64();
私有静态字符串getSignature(字符串url、字符串参数)
抛出不支持的CodingException、NoSuchAlgorithmException、,
InvalidKeyException{
StringBuilder base=新的StringBuilder();
base.append(“GET&”);
base.append(url);
基数。追加(“&”);
base.append(params);
System.out.println(“创建签名…”+base);
byte[]keyBytes=(secret+“&”).getBytes(ENC);
SecretKey key=newsecretkeyspec(keyBytes,HMAC_SHA1);
Mac Mac=Mac.getInstance(HMAC_SHA1);
mac.init(密钥);
返回新字符串(base64.encode(mac.doFinal)(base.toString().getBytes(
ENC))),ENC.)trim();
}
公共静态void main(字符串[]args)抛出ClientProtocolException,
IOException、URISyntaxException、InvalidKeyException、,
NoSuchAlgorithmException{
HttpClient HttpClient=新的DefaultHttpClient();
List qparams=new ArrayList();
//这些参数应按键排序
添加(新的BasicNameValuePair(“oauth_consumer_key”,key));
添加(新的BasicNameValuePair(“oauth_nonce”)
+(int)(Math.random()*100000000));
添加(新的BasicNameValuePair(“oauth\u签名\u方法”),
“HMAC-SHA1”);
添加(新的BasicNameValuePair(“oauth_时间戳”)
+(System.currentTimeMillis()/1000));
//生成oauth_签名
字符串签名=getSignature(
URLEncoder.encode(“www.buhoplace.net”,ENC),
encode(URLEncodedUtils.format(qparams,ENC),ENC));
//将其添加到参数列表中
添加(新的BasicNameValuePair(“oauth_签名”,签名));
//生成导致访问令牌和令牌密钥的URI。
URI=URIUtils.createURI(“http”,“www.buhoplace.net”,-1,
“/wc api/v2/products”,URLEncodedUtils.format(qparams,ENC),
无效);
System.out.println(“url llamada”+uri);
HttpGet HttpGet=新的HttpGet(uri);
//输出响应内容。
System.out.println(“Resultado de la llamada”);
HttpResponse response=httpclient.execute(httpget);
HttpEntity=response.getEntity();
如果(实体!=null){
InputStream instream=entity.getContent();
内伦;
字节[]tmp=新字节[2048];
而((len=流内读取(tmp))!=-1){
System.out.println(新字符串(tmp,0,len,ENC));
}
}
}

如何解决此问题?

这是您的答案。请仔细查看此片段,其中有一个与Woocommerce合作的本地网站。在此请求中,api按钮可获取此本地网站的订单。 不要打断签名参数的序列。它以唯一的序列追加以生成正确的签名

public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";
        private static final String CONSUMERKEY = "ck_cfaf32e212c68c7c66b9a8f43625af72";
        private static final String CONSUMERSECRET = "cs_814f422a33bc737d188cb6a05ea4897c";
        private static final String METHOD = "HMAC-SHA1";
        private static final String URL = "http://192.168.1.21/wordpress/wc-api/v2/orders";
        private static final String PARAMNAME_KEY = "oauth_consumer_key";
        private static final String PARAMNAME_SECRET = "oauth_consumer_secret";
        private static final String PARAMNAME_NONCE = "oauth_nonce";
        private static final String PARAMNAME_TIMESTAMP = "oauth_timestamp";
        private static final String PARAMNAME_SIGNATURE = "oauth_signature";
        private static final String PARAMNAME_SIGNATURE_METHOD = "oauth_signature_method";

        /**
         * Returns a new instance of this fragment for the given section number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        Button bRequest, bClear;
        TextView tvResponse;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            bRequest = (Button) rootView.findViewById(R.id.button1);
            bClear = (Button) rootView.findViewById(R.id.button2);
            bRequest.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    new TestApi().execute();
                }
            });
            bClear.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    tvResponse.setText("");
                }
            });
            tvResponse = (TextView) rootView.findViewById(R.id.textView1);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(getArguments().getInt(
                    ARG_SECTION_NUMBER));
        }

        public String getSignature() {
            ArrayList<String> names = new ArrayList<String>();
            names.add(PARAMNAME_KEY);
            names.add(PARAMNAME_TIMESTAMP);
            names.add(PARAMNAME_NONCE);
            names.add(PARAMNAME_SIGNATURE_METHOD);
            return null;
        }

        class TestApi extends AsyncTask<Void, Void, Void> {
            ProgressDialog d;
            JSONParser jparser = new JSONParser();
            JSONObject response;
            List<NameValuePair> parameters;

            @Override
            protected Void doInBackground(Void... params) {
                String timestamp = System.currentTimeMillis() / 1000 + "";
                String nonce =  (Math.random() * 100000000) + "";
                parameters = new ArrayList<NameValuePair>();
                parameters.add(new BasicNameValuePair("oauth_consumer_key",
                        CONSUMERKEY));
                // parameters.add(new
                // BasicNameValuePair("oauth_consumer_secret",
                // CONSUMERSECRET));
                parameters.add(new BasicNameValuePair("oauth_timestamp",
                        timestamp));
                parameters.add(new BasicNameValuePair("oauth_nonce",
                        nonce));
                parameters.add(new BasicNameValuePair("oauth_signature_method",
                        "HMAC-SHA1"));
                String encoded_base_url = "GET&" + URLEncoder.encode(URL) + "&";
                Log.d("encoded url", encoded_base_url);
                StringBuilder builder = new StringBuilder();
                builder.append(PARAMNAME_KEY + "=" + CONSUMERKEY + "&");
                // builder.append(PARAMNAME_SECRET + "=" + CONSUMERSECRET +
                // "&");

                builder.append(PARAMNAME_NONCE + "="
                        + nonce + "&");

                builder.append(PARAMNAME_SIGNATURE_METHOD + "=" + METHOD + "&");
                builder.append(PARAMNAME_TIMESTAMP + "=" + timestamp);
                String str = builder.toString();
                str = URLEncoder.encode(str);
                Log.d("prepared string", str);
                String signature = encoded_base_url + str;
                String encoded = "";
                try {
                    Mac mac = Mac.getInstance(METHOD);
                    byte[] key = CONSUMERSECRET.getBytes("utf-8");
                    SecretKey secretKey = new SecretKeySpec(key, METHOD);
                    mac.init(secretKey);
                    byte[] signaturebytes = mac.doFinal(signature
                            .getBytes("utf-8"));
                    encoded = Base64.encodeToString(signaturebytes,
                            Base64.DEFAULT).trim();

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Log.d("signature", encoded);
                parameters.add(new BasicNameValuePair(PARAMNAME_SIGNATURE,
                        encoded));
                response = jparser.makeHttpRequest(
                        URL,
                        "GET", parameters);
                return null;
            }

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                d = new ProgressDialog(getActivity());
                d.show();
            }

            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                d.dismiss();
                tvResponse.setText(response.toString());
            }

        }
    }
公共静态类占位符片段扩展片段{
/**
*表示此文件节号的片段参数
*碎片。
*/
私有静态最终字符串ARG\u SECTION\u NUMBER=“SECTION\u NUMBER”;
私有静态最终字符串CONSUMERKEY=“ck_cfaf32e212c68c7c66b9a8f43625af72”;
私有静态最终字符串CONSUMERSECRET=“cs_814f422a33bc737d188cb6a05ea4897c”;
私有静态最终字符串方法=“HMAC-SHA1”;
私有静态最终字符串URL=”http://192.168.1.21/wordpress/wc-api/v2/orders";
私有静态最终字符串PARAMNAME\u KEY=“oauth\u consumer\u KEY”;
私有静态最终字符串PARAMNAME_SECRET=“oauth_consumer_SECRET”;
私有静态最终字符串PARAMNAME\u NONCE=“oauth\u NONCE”;
私有静态最终字符串PARAMNAME\u TIMESTAMP=“oauth\u TIMESTAMP”;
私有静态最终字符串PARAMNAME\u SIGNATURE=“oauth\u SIGNATURE”;
私有静态最终字符串PARAMNAME\u SIGNATURE\u METHOD=“oauth\u SIGNATURE\u METHOD”;
/**
*返回给定节号的此片段的新实例。
*/
公共静态占位符片段newInstance(int sectionNumber){
占位符片段=新占位符片段();
Bundle args=新Bundle();
参数Putin(参数段号,段号);
fragment.setArguments(args);
返回片段;
}
公共占位符片段(){
}
纽扣酿造,bClear;
文本视图响应;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.fragment_main,容器,
假);
bRequest=(按钮)rootView.findViewById(R.id.button1);
bClear=(按钮)rootView.findViewById(R.id.button2);
bRequest.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
newtestapi().execute();
}
});
bClear.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
tvResponse.setText(“”);
}
});
tvResponse=(TextView)rootView.findViewById(R.id.textView1);
返回rootView;
}
@凌驾
公共事务主任(活动){