微信小程序第一步,微信api(附代碼鏈接)

全部是代碼

下部附有網盤鏈接

public class WeiXinConfigModel {
public String timestamp;


public String signature;


public String noncestr;
public String appid;


public String getAppid() {
return appid;
}


public void setAppid(String appid) {
this.appid = appid;
}


public String getNoncestr() {
return noncestr;
}


public void setNoncestr(String noncestr) {
this.noncestr = noncestr;
}


public String getTimestamp() {
return timestamp;
}


public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}


public String getSignature() {
return signature;
}


public void setSignature(String signature) {
this.signature = signature;
}


}
import java.sql.Timestamp;


import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name = "accesstoken")
public class AccessToken {
@Id
private String accessTokenId;
private String appid;
private String secret;
private String access_token;
private String create_time;
private Timestamp createTimeStamp;


public Timestamp getCreateTimeStamp() {
return createTimeStamp;
}
public void setCreateTimeStamp(Timestamp createTimeStamp) {
this.createTimeStamp = createTimeStamp;
}
public String getAccessTokenId() {
return accessTokenId;
}
public void setAccessTokenId(String accessTokenId) {
this.accessTokenId = accessTokenId;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getCreate_time() {
return create_time;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}


}

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.carlock.model.AccessToken;
import com.carlock.model.WeiXinConfigModel;
import com.carlock.service.AccessTokenService;
@Controller
@RequestMapping("/weixin")
public class WeiXinController1 {
Logger logger = Logger.getLogger(this.getClass());
static String AppId = "wxb2fdcdfsdfdsfs";// 第三方用戶唯一憑證
static String secret = "1cd9198e6bc4sdsdsdsdsds";// 第三方用戶唯一憑證密鑰,即appsecret


@Autowired
AccessTokenService accessTokenService;


public static String getAccessToken() {
String access_token = "";
String grant_type = "client_credential";// 獲取access_token填寫client_credential
// 這個url鏈接地址和參數皆不能變
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + AppId + "&secret="
+ secret;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必須是get方式請求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 連接超時30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 讀取超時30秒
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demo=JSON.parseObject(message);
access_token=demo.getString("access_token");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return access_token;
}


public static String getTicket(String access_token) {
String ticket = null;
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";// 這個url鏈接和參數不能變
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必須是get方式請求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 連接超時30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 讀取超時30秒
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSON.parseObject(message);
ticket = demoJson.getString("ticket");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return ticket;
}


public static String SHA1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字節數組轉換爲 十六進制 數
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();


} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}


@RequestMapping("/index")
@ResponseBody
public WeiXinConfigModel Index(HttpServletRequest request, HttpServletResponse response, String address,
AccessToken accessToken,Model model) {
// 1、獲取AccessToken

String access_token ="";
if(access_token==null||access_token==""){
accessToken=accessTokenService.select();
if(accessToken.getAccess_token()==null||accessToken.getAccess_token().equals("")||accessToken.getAccess_token().length()<=0){
access_token=getAccessToken();
saveAccessToken(access_token);
}else{
//如果以前獲取過
//access_token有失效時間,先檢查以前存入的是不是已經失效
Long now = new Date().getTime();//獲取當前時間的
//當前時間減去存入時間,看看是不是在失效時間範圍7200S內,我這裏設置的驗證時間小於7200s
Long count = now - accessToken.getCreateTimeStamp();// 1000*60*2
int nowLong = 1000 * 60 * 100;// 100分鐘
              if (count > nowLong) {//失效了  重新獲取存入
              access_token=getAccessToken();
     saveAccessToken(access_token);
              }else{//未失效,下面直接調用,這個可以不要
              
              }
}

}
// 2、獲取Ticket
String jsapi_ticket = getTicket(access_token);
// 3、時間戳和隨機字符串
String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);// 隨機字符串
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);// 時間戳
// 5、將參數排序並拼接字符串
String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="
+ address;
// 6、將字符串進行sha1加密
String signature = SHA1(str);
WeiXinConfigModel weixin = new WeiXinConfigModel();
weixin.setSignature(signature);
weixin.setNoncestr(noncestr);
weixin.setTimestamp(timestamp);
weixin.setAppid(AppId);
return weixin;
}

//保存access_token

public void saveAccessToken(String access_token){
try {
AccessToken accessToken=new AccessToken();
accessToken.setAccess_token(access_token);//AppId
accessToken.setAppid(AppId);
accessToken.setSecret(secret);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設置日期格式
Date date=new Date();
String time=df.format(date);
accessToken.setCreate_time(time);
accessTokenService.insert(accessToken); //保存accessToken,可以根據自己情況存入數據庫
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}

前端 微信js插件

在需要調用JS接口的頁面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.2.0.js

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">
//獲取微信驗證
$(function() {
var signature;
var noncestr;
var timestamp;
var appid;
var url1 = window.location.href;  //獲取當前路徑  記住域名一定要在微信公衆號添加了安全域名配置
$(document).ready(
function() {
$.ajax({
type : "post",
url : "/weixin/index?address="+ window.location.href,//通過後臺請求,獲取微信驗證信息
dataType : "json",
contentType : "application/json; charset=utf-8",
success : function(data) {
signature = data.signature;
noncestr = data.noncestr;
timestamp = data.timestamp; 
appid = data.appid;
wx.config({
debug : false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
appId : appid, // 必填,公衆號的唯一標識
timestamp : timestamp1, // 必填,生成簽名的時間戳
nonceStr : noncestr,// 必填,生成簽名的隨機串
signature : signature,// 必填,簽名,見附錄1
jsApiList : [ 'scanQRCode' ]// 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
});
//config信息驗證失敗
wx.error(function(res) {
alert("驗證失敗");
});
},
error : function(data) {
alert('網絡錯誤');
}
});
});
});


//點擊掃碼按鈕
$("#scanRCode").click(function(){
wx.scanQRCode({
needResult : 1,//默認0,掃描結果,微信處理,1,直接返回掃描結果
scanType : [ "qrCode" ],//指定掃二維碼
success : function(res) {
var url = res.resultStr;//result爲1時,掃碼返回的結果  url即爲二維碼中數據
if(url.indexOf(",")>=0){
                     var getresult = url.split(',');
                     var getresult1 = getresult[1];
                     //彈出二維碼結果
                    alert(getresult1);
                 }else{
                     //有問題
                 }
}
});    
});

鏈接

鏈接:https://pan.baidu.com/s/1_8Hs6V06GdX7ia5fYV4MlQ
提取碼:7s8u

發佈了21 篇原創文章 · 獲贊 29 · 訪問量 6302
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章