国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

uniapp+微信小程序獲取openId,獲取access_token,訂閱消息模板,java后臺發(fā)送消息

這篇具有很好參考價值的文章主要介紹了uniapp+微信小程序獲取openId,獲取access_token,訂閱消息模板,java后臺發(fā)送消息。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

目錄

1.前期準備

2.用戶訂閱消息

3.獲取openId(uniapp)

4.獲取access_token

5.發(fā)送消息

6.請求的代碼Springboot(自己寫有發(fā)送請求方法的可以不用看)

1.前期準備

在微信公眾號申請訂閱消息

在公共模板這里選用模板,模板種類跟小程序設(shè)置的類目有關(guān),只有特殊的類目有長期訂閱模板

類目可以在設(shè)置中修改

2.用戶訂閱消息

選用模板后點擊詳情查看模板的id

在小程序上編寫以下代碼(這個是uniapp框架的代碼)

uni.requestSubscribeMessage({
					tmplIds:['1QO7f6SdIiw7loXtIhaIL5IKl4Ze0lS2moDVnjaAlLQ'],
					complete:(res)=>{
						console.log(res)
					}
				})

微信原生大概是這樣的,沒試過哈

wx.requestSubscribeMessage({
					tmplIds:['1QO7f6SdIiw7loXtIhaIL5IKl4Ze0lS2moDVnjaAlLQ'],
					complete:(res)=>{
						console.log(res)
					}
				})

?參考鏈接

?其中tmplIds就是我們選用模板的id,是個數(shù)組,最多三個。

用戶選擇確定后便可以進行消息發(fā)送。

3.獲取openId(uniapp)

獲取code?

uni.login({
				provider:"weixin",
				success:(loginRes)=>{
					console.log(loginRes.code);
					
				}
			})

后臺通過code獲取用戶的openId

public String getOpenId(HttpServletRequest request, String code){
        SendParam sendParam = new SendParam();
        sendParam.setUrl("https://api.weixin.qq/sns/jscode2session");
        Map<String,String> param = new HashMap();
        param.put("appid","微信小程序的appid");
        param.put("secret","微信小程序的secret");
        param.put("js_code","用戶通過登錄方法獲取的code");
        param.put("grant_type","authorization_code");
        sendParam.setGetParam(param);
        SendReturn sendReturn =  SendUtils.sendGet(sendParam);
        System.out.println(sendReturn.getReturnString());
        return ReturnData.reJson(ReturnCode.MC001);
    }

用get請求訪問

https://api.weixin.qq/sns/jscode2session

例如

https://api.weixin.qq/sns/jscode2session?appid=xxx&secret=xxx&js_code=xxx&grant_type=authorization_code

訪問成功就能獲取到用戶的openId

4.獲取access_token

 public String getAccessToken(){
        SendParam sendParam = new SendParam();
        sendParam.setUrl("https://api.weixin.qq/cgi-bin/token");
        Map<String,String> param = new HashMap();
        param.put("grant_type","client_credential");
        param.put("appid","小程序的appid");
        param.put("secret","小程序的secret");
        sendParam.setGetParam(param);
        SendReturn sendReturn =  SendUtils.sendGet(sendParam);
        return ReturnData.reJson(ReturnCode.MC001);
    }

用get請求訪問

https://api.weixin.qq/cgi-bin/token

例如

https://api.weixin.qq/cgi-bin/token?grant_type=client_credential&appid=xxx&secret=xxx

訪問成功即可獲取到access_token

access_token是有時效的,默認7200秒。使用的時候記得看是否過期。

5.發(fā)送消息

public String send(){
        SendParam sendParam = new SendParam();
        sendParam.setUrl("https://api.weixin.qq/cgi-bin/message/subscribe/send?access_token=57_CRjtQyjioD2Qe46gxDicfRifwTN-9kfteW9Onc1ZlWizniNXH1ww1j7FUhWc1WXM9ja7GXRPm_mtTIEdGdt5a7lCH9118Axz2Rm0Ku2h57dhMSYiAtwP6QxBr1h62x55bN4bsb7ajFlZ5m73XCSaAAALQG");
        Map param = new HashMap();
        param.put("touser","otnoE5Ry_89dahJ2_OhxIXVcLBPg");
        param.put("template_id","1QO7f6SdIiw7loXtIhaIL5IKl4Ze0lS2moDVnjaAlLQ");
        Map dataMap = new HashMap();
        dataMap.put("thing1",new HashMap<String,String>(){{put("value","2");}});
        dataMap.put("thing2",new HashMap<String,String>(){{put("value","2");}});
        dataMap.put("thing3",new HashMap<String,String>(){{put("value","2021-01-01 00:00:00");}});
        param.put("data", dataMap);
        sendParam.setPostParam(param);
        SendReturn sendReturn =  SendUtils.SendPost(sendParam);
        return ReturnData.reJson(ReturnCode.MC001);
    }

發(fā)送post請求?。?!post請求!?。?/strong>

https://api.weixin.qq/cgi-bin/message/subscribe/send?access_token=xxxxx

其中access_token就是第四步獲取到的access_token,參數(shù)要寫到url中

之后就是要發(fā)送的數(shù)據(jù)

touser:要發(fā)送給用戶的openId,獲取方法看第三步
template_id:模板id,第一步選擇模板時可以看到模板的id
data:要發(fā)送的數(shù)據(jù),根據(jù)模板要求的數(shù)據(jù)來裝配

比如模板要求的數(shù)據(jù)是這樣的

那么最后拼湊的數(shù)據(jù)是這樣的

data:{
    thing1:{value:"123"},
    thing2:{value:"123"},
    thing3:{value:"123"},
}

整體數(shù)據(jù)格式

{
    "touser":"XXXX",
    "template_id":"xxxxx",
    "data":{
        "thing1":{"value":"123"},
        "thing2":{"value":"234"},
        "thing3":{"value":"456"}
    }
}

用postMan看的話是這樣的

請求成功后即可。

要注意的是,如果用的是一次性模板,用戶訂閱一次,服務(wù)端才能發(fā)送一次,若需要發(fā)送兩次就需要用戶訂閱兩次(也就是說要訂閱兩次)?。。。。。浚???

長期模板的話,用戶點擊訂閱后就不需要重復(fù)訂閱,服務(wù)端也能一直發(fā)送消息。

6.請求的代碼Springboot(自己寫有發(fā)送請求方法的可以不用看)

代碼垃圾,輕點噴?勿噴

SendParam
package ??????;

import org.springframework.http.HttpMethod;

import java.util.Map;


public class SendParam<T> {
    private String url;
    private Object postParam;
    private Map<String,String> getParam;
    private HttpMethod sendType;
    private Class<T> classTr;

    public SendParam() {
        this.sendType = HttpMethod.GET;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Object getPostParam() {
        return postParam;
    }

    public void setPostParam(Object postParam) {
        this.postParam = postParam;
    }

    public Map<String, String> getGetParam() {
        return getParam;
    }

    public void setGetParam(Map<String, String> getParam) {
        this.getParam = getParam;
    }

    public HttpMethod getSendType() {
        return sendType;
    }

    public void setSendType(HttpMethod sendType) {
        this.sendType = sendType;
    }

    public Class<T> getClassTr() {
        return classTr;
    }

    public void setClassTr(Class<T> classTr) {
        this.classTr = classTr;
    }
}
SendReturn
package ???????;

import org.springframework.http.HttpStatus;

public class SendReturn<T> {
    private boolean isSuccess;
    private String returnString;
    private T obj;
    private HttpStatus statusCode;
    private int statusCodeValue;


    public SendReturn() {
        this.isSuccess=true;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean success) {
        isSuccess = success;
    }

    public String getReturnString() {
        return returnString;
    }

    public void setReturnString(String returnString) {
        this.returnString = returnString;
    }

    public T getObj() {
        return obj;
    }

    public void setObj(T obj) {
        this.obj = obj;
    }

    public HttpStatus getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(HttpStatus statusCode) {
        this.statusCode = statusCode;
    }

    public int getStatusCodeValue() {
        return statusCodeValue;
    }

    public void setStatusCodeValue(int statusCodeValue) {
        this.statusCodeValue = statusCodeValue;
    }
}
SendUtils
package ??????;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Map;

@Component
public class SendUtils {

    private static RestTemplate restTemplate;

    @Autowired
    ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        SendUtils.restTemplate = applicationContext.getBean(RestTemplate.class);
    }

    private static Gson gson = new Gson();


    /**
     * 發(fā)送get請求
     * @param send
     * @return
     */
    public static SendReturn sendGet(SendParam send){
        String url = send.getUrl()+"?";
        if(send.getGetParam()!=null){
            Map<String,String> map = send.getGetParam();
            for(Map.Entry<String,String> entity : map.entrySet()){
                url += entity.getKey()+"="+entity.getValue()+"&";
            }
            url = url.substring(0,url.length()-1);
        }

        SendReturn sendReturn = new SendReturn();
        try{
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            if(send.getClassTr()!=null){
                Object o = gson.fromJson(responseEntity.getBody(),send.getClassTr());
                sendReturn.setObj(o);
            }
            sendReturn.setStatusCode(responseEntity.getStatusCode());
            sendReturn.setStatusCodeValue(responseEntity.getStatusCodeValue());
            sendReturn.setReturnString(responseEntity.getBody());
        }catch (Exception e){
            System.out.println(e);
            sendReturn.setSuccess(false);
        }
        return sendReturn;
    }


    /**
     * 發(fā)送post請求
     * @param send
     * @return
     */
    public static SendReturn SendPost(SendParam send){
        SendReturn sendReturn = new SendReturn();
        try{
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(send.getUrl(),send.getPostParam(),String.class);
            if(send.getClassTr()!=null){
                Object o = gson.fromJson(responseEntity.getBody(),send.getClassTr());
                sendReturn.setObj(o);
            }
            sendReturn.setStatusCode(responseEntity.getStatusCode());
            sendReturn.setStatusCodeValue(responseEntity.getStatusCodeValue());
            sendReturn.setReturnString(responseEntity.getBody());
        }catch (Exception e){
            System.out.println(e);
            sendReturn.setSuccess(false);
        }
        return sendReturn;
    }




}

修改請求配置(這里用的是okhttp哈)

RestTemplateConfig
package ????;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * 數(shù)據(jù)請求配置
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }


}

maven上要加上okhttp3和gson的依賴哈

pom.xml文章來源地址http://www.zghlxwxcb.cn/news/detail-777393.html

<dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
</dependency>

<dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
</dependency>

到了這里,關(guān)于uniapp+微信小程序獲取openId,獲取access_token,訂閱消息模板,java后臺發(fā)送消息的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 微信小程序報錯:invalid credential, access_token is invalid or not latest

    獲取到了 access_token,用 access_token 去生成小程序二維碼報錯: invalid credential, access_token is invalid or not latest 在 微信開放社區(qū) 搜索解決方案 獲取accessToken接口 Access token 的存儲與更新 生成微信小程序碼接口(永久有效,數(shù)量暫無限制) access_token 的有效期是 2小時 ,看下是不是

    2024年02月10日
    瀏覽(17)
  • 微信小程序獲取openId

    在微信小程序中,我們無法直接從客戶端獲取用戶的openid,因為openid是保存在微信服務(wù)器上的。但是,我們可以通過微信提供的登錄接口,使用用戶授權(quán)登錄的方式獲取用戶的openid。 具體步驟如下: 1. 在小程序中引入`wx.login`方法,調(diào)用該方法會返回一個`code`,這個`code`用于

    2024年02月15日
    瀏覽(29)
  • uniapp微信小程序獲得openid

    可以自動獲取或點擊按鈕獲取 獲取openid 注意:一般都是將code值傳到后端去獲取openid,因為在前端可能會被抓包或爬取到你的appid和secret,不安全,如果放在后端獲取openid,除非你的服務(wù)器被攻擊了,不然就是安全的。下面的實例是在前端直接獲取的,這個明白后,可以直接

    2024年02月06日
    瀏覽(21)
  • 微信小程序獲取openid流程

    調(diào)用wx.login(OBJECT) 獲取登錄憑證(code)進而換取用戶登錄態(tài)信息,包括用戶的唯一標識(openid)及本次登錄的會話密鑰(session_key)等。用戶數(shù)據(jù)的加解密通訊需要依賴會話密鑰完成。 返回數(shù)據(jù)信息: { errMsg: 調(diào)用結(jié)果 code: 用戶登錄憑證(有效期五分鐘)。開發(fā)者需要在開發(fā)

    2024年02月14日
    瀏覽(23)
  • 微信小程序----API、獲取openid、消息訂閱

    微信小程序----API、獲取openid、消息訂閱

    https://www.w3xue.com/mobile/wxminiapp/hpm41q8p.html 基礎(chǔ): API,全稱Application Programming Interface,即應(yīng)用程序編程接口。 API 是一些預(yù)先定義函數(shù),目的是用來提供應(yīng)用程序與開發(fā)人員基于某軟件或者某硬件得以訪問一組例程的能力,并且無需訪問源碼或無需理解內(nèi)部工作機制細節(jié)。 API

    2024年02月09日
    瀏覽(22)
  • 【微信小程序】通過云函數(shù)獲取用戶openid

    1.pages同級目錄下新建新文件夾,命名為cloudFunctions(其他名字也可以)。 2.project.config.json中添加以下內(nèi)容,值為上一步創(chuàng)建的文件夾名字。編譯一次后上一步創(chuàng)建的文件夾前圖標就帶“云”了。 3.app.js內(nèi)的App中添加 1.右擊cloudFunctions文件夾,點擊【新建Node.js云函數(shù)】,命名為

    2024年02月10日
    瀏覽(95)
  • 微信小程序如何獲取微信號的唯一標識(openid)

    微信小程序如何獲取微信號的唯一標識(openid)

    1.獲取微信登錄憑證 2.登錄憑證傳回后端獲取openid,前端直接調(diào)用接口獲取openid正式上線代碼審核過不去。 3.后端代碼(直接返回的openid中含有secret,可發(fā)布,但是會提醒你存在安全漏洞,所以對openid進行截取拼接) 3.獲取AppSecret和AppID 登錄微信公眾平臺 開發(fā)——開發(fā)管理——開發(fā)

    2024年02月08日
    瀏覽(18)
  • 微信小程序內(nèi)嵌H5頁面獲取openid+分享功能

    主要實現(xiàn)功能:1.通過webview實現(xiàn)小程序內(nèi)嵌H5頁面 ? ? ? ? ? ? ? ? ? ? ? ? ?2.在H5頁面獲取到用戶的openid ? ? ? ? ? ? ? ? ? ? ? ? ?3.在H5頁面實現(xiàn)分享獲取到分享人的openid和被分享者的openid 代碼實現(xiàn): 1.通過webview實現(xiàn)小程序內(nèi)嵌H5頁面 傳參:在地址后面加入的參數(shù)就是我

    2024年04月23日
    瀏覽(106)
  • 微信小程序登錄獲取用戶唯一標識OpenId,(SpringBoot項目)

    微信小程序登錄獲取用戶唯一標識OpenId,(SpringBoot項目)

    微信小程序的登錄,需要獲取到用戶的唯一標識OpenId,這里只涉及到后端代碼,所以前提是前端申請了一個小程序并且有了appid和secret。 文章目錄 一、微信小程序登錄流程 二、代碼實現(xiàn) 1.引入相關(guān)依賴 2.代碼實現(xiàn) 實際項目經(jīng)驗分享 先上官方開發(fā)文檔連接 小程序登錄 | 微信

    2024年02月12日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包